python socket通訊程式設計實現檔案上傳程式碼例項
阿新 • • 發佈:2020-01-09
這篇文章主要介紹了python socket通訊程式設計實現檔案上傳程式碼例項,文中通過示例程式碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
寫一個file_receive.py和一個file_send.py程式,由file_send.py上傳一個檔案,file_receive.py接收上傳的檔案,寫到指定的包內
#file_receive.py import socket,subprocess,os BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sk = socket.socket() address = ('127.0.0.1',8001) sk.bind(address) sk.listen(3) conn,addr = sk.accept() fileinfo = conn.recv(1024) filename,filesize = str(fileinfo,'utf8').split('|') #filename = str(filename,'utf8') #filesize = int(str(filesize,'utf8')) path = os.path.join(BASE_DIR,'file_recv',filename) f = open(path,'wb') has_received = 0 while has_received != int(filesize): data = conn.recv(1024) f.write(data) has_received += len(data) f.close() print('well done') sk.close()
#file_send.py import socket,8001) sk.connect(address) filename = input("please input filename:") path = os.path.join(BASE_DIR,filename) filesize = os.stat(path).st_size fileinfo = '%s|%s'%(filename,str(filesize)) sk.sendall(bytes(fileinfo,'utf8')) f = open(path,'rb') has_sent = 0 while has_sent != int(filesize): data = f.read(1024) sk.sendall(data) has_sent += len(data) print('well done!') f.close() sk.close()
檔案執行後,實現了將file_send.py上傳的test.png檔案上傳到當前路徑下的file_recv包內.
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。