Fork me on GitHub
随笔 - 226,  文章 - 0,  评论 - 3,  阅读 - 50419
复制代码
import socket,os,json,struct
SHARE_DIR=r'D:\python13期\网络编程\文件处理\SHARE'
class FtpServer:
    def __init__(self,host,port):
        self.host=host
        self.port=port
        self.server=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        self.server.bind((self.host,self.port))
        self.server.listen(5)
    def serve_forever(self):
        print('server starting...')
        while True:
            self.conn,self.client_addr=self.server.accept()
            print(self.client_addr)
            while True:
                try:
                    data=self.conn.recv(1024)
                    if not data:break
                    params=json.loads(data.decode('utf-8'))
                    cmd=params[0]
                    if hasattr(self,cmd):
                        func=getattr(self,cmd)
                        func(params)
                    else:
                        print('\033[45mcmd not exists\033[0m')
                except ConnectionResetError:break
            self.conn.close()
        self.server.close()
    def get(self,params):
        filename=params[1]
        filepath=os.path.join(SHARE_DIR,filename)
        if os.path.exists(filepath):
            headers = {'filename': filename,
                       'md5': '123fvs54',
                       'file_size': os.path.getsize(filepath)}
            headers_json = json.dumps(headers)
            headers_bytes = headers_json.encode('utf-8')
            self.conn.send(struct.pack('i', len(headers_bytes)))
            self.conn.send(headers_bytes)
            with open(filepath,'rb')as f:
                for line in f:
                    self.conn.send(line)
    def put(self):
        pass
if __name__ == '__main__':
    server=FtpServer('127.1.2.3',8999)
    server.serve_forever()
复制代码
posted on   OBOS  阅读(173)  评论(0编辑  收藏  举报
< 2025年1月 >
29 30 31 1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31 1
2 3 4 5 6 7 8

点击右上角即可分享
微信分享提示