代碼筆記 | 一個用python實現的簡單的文件服務器

 
#!/usr/bin/env python3
"""
實現客戶端和服務器端邏輯,通過套接字從服務器傳輸任意文件到客戶端;
使用一個簡單的控制信息協議,而不是單獨的套接字,用於控制和數據(如在ftp上)
分派每個客戶端請求到一個線程處理,通過分塊,循環傳輸整個文件;
"""
import sys,os,time
import _thread as thread
from socket import *
  
blksz=1024
defhost='localhost'
defport=50001
  
helptext="""
usage...
server=>getfile.py -mode serve          [-port nnn] [-host hhh|localhost]
client=>getfile.py [-mode client] -file fff [-port nnn] [-host hhh|localhost]
"""
def now():
        return time.asctime()
  
def parsecommandline():
        dict={}
        args=sys.argv[1:]
        while len(args) >=2:
                dict[args[0]]=args[1]
                args=args[2:]
        return dict
  
def client(host,port,filename):
        sock=socket()
        sock.connect((host,port))
        sock.send((filename +'\\n').encode())
        dropdir=os.path.split(filename)[1]
        file=open(dropdir,'wb')
        while True:
                data=sock.recv(1024)
                if not data: break
                file.write(data)
        sock.close()
        file.close()
        print('client got',filename,'at',now())
  
def serverthread(clientsock):
        sockfile=clientsock.makefile('r')
        filename=sockfile.readline()[:-1]
        try:
                file=open(filename,'rb')
                while True:
                        byts=file.read(blksz)
                        if not byts: break
                        sent=clientsock.send(byts)
                        assert sent == len(byts)
        except:
                print('error downloading file on server',filename)
        clientsock.close()
  
def server(host,port):
        serversock=socket()
        serversock.bind((host,port))
        serversock.listen(5)
        while True:
                clientsock,addr=serversock.accept()
                print('server connect by',addr,'at',now())
                thread.start_new_thread(serverthread,(clientsock,))
  
def main(args):
        host=args.get('-host',defhost)
        port=int(args.get('-port',defport))
        if args.get('-mode') == 'server':
                if host == 'localhost': host=''
                server(host,port)
        elif args.get('-file'):
                client(host,port,args['-file'])
        else:
                print(helptext)
  
if __name__ == '__main__':
        args=parsecommandline()
        main(args)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章