Python網路程式設計(三)-基於tcp協議實現檔案傳輸(基礎版)
阿新 • • 發佈:2020-12-05
server.py
#服務端接收 import json import socket sk = socket.socket() sk.bind(('127.0.0.1',9000)) sk.listen() conn,addr = sk.accept() msg = conn.recv(1024).decode('utf-8') msg = json.loads(msg) print(msg['filename'],msg['filesize']) with open(msg['filename'],mode='wb') as f: content = conn.recv(msg['filesizeserver端程式碼']) print('--filelen',len(content)) f.write(content) conn.close() sk.close()
client.py
#客戶端傳送 import os import json import socket sk = socket.socket() sk.connect(('127.0.0.1',9000)) #需要傳送檔名,檔案大小 abs_path = r'E:\project\tcp-testfile' # os.path模組獲取檔名 filename = os.path.basename(abs_path)client端程式碼# os.path模組獲取檔案大小 filesize = os.path.getsize(abs_path) dic = {'filename':filename,'filesize':filesize} # 網編中傳輸資料,常用的是json型別 str_dic = json.dumps(dic) sk.send(str_dic.encode('utf-8')) with open(abs_path,mode='rb') as f: content = f.read() sk.send(content) sk.close()