码迷,mamicode.com
首页 > 其他好文 > 详细

文件处理服务端

时间:2020-01-03 21:29:59      阅读:94      评论:0      收藏:0      [点我收藏+]

标签:cmd   lse   _for   struct   ftps   error   recv   serve   end   

import socket,os,json,struct
SHARE_DIR=rD:\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()

文件处理服务端

标签:cmd   lse   _for   struct   ftps   error   recv   serve   end   

原文地址:https://www.cnblogs.com/0B0S/p/12146623.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!