FTP Server Upload

Keywords: socket Python network

When each client is on the server side for two years, a new thread starts interacting with the client. If they download different files, it means that they have the same number of IO operations as the client side, which is equivalent to opening the same number of buffers as the client side.They are slow because of IO read and write speed and network latency.All threads can read IO, and the underlying IO thread is asynchronous, but locks are required when writing.

  • server.py file
#!/usr/bin/env python
#coding:utf-8
import SocketServer
import os
class MyServer(SocketServer.BaseRequestHandler):
    def handle(self):
        base_path = "E:/temp"
        conn = self.request
        print 'connected...'
        pre_data = conn.recv(1024)
            #Get Request Method, File Name, Size
        cmd,file_name,file_size = pre_data.split('|')
            #Size of received file
        recv_size = 0
            #Upload Path Stitching
        file_dir = os.path.join(base_path,file_name)
        f = file(file_dir,'wb')
        Flag = True
        while Flag:
            if int(file_size)>recv_size:
                data = conn.recv(1024)
                recv_size += len(data)
                f.write(data)
            else:
                recv_size = 0
                Flag =False
        print 'unpload successed'
        f.close()
instance = SocketServer.ThreadingTCPServer(('127.0.0.1',9999),MyServer)
instance.serve_forever()
  • client.py file
#!/usr/bin/env python
#coding:utf-8
import socket
import os
ip_port = ('127.0.0.1',9999)
sk = socket.socket()
sk.connect(ip_port)
while True:
    input = raw_input('path: ')
    cmd,path = input.split('|')
    #Define rules, upload rules.

    file_name = os.path.basename(path)
    file_size = os.path(path).st_size

    sk.send(cmd+"|"+file_name+"|"+str(file_size))
    #Send command, file name, size 

    send_size = 0
    f = file(path,'rb')
    Flag = True
    while Flag:
        if(send_size +1024>file_size):
            data  = f.read(file._size-send_size)
            Flag = False
        else:
            data = f.read (1024)
            send_size  += 1024
        sk.send(data)
    f.close()
sk.close()

Posted by daven on Sun, 10 May 2020 09:11:29 -0700