Python网络编程(三)-基于tcp协议实现文件传输(基础版)
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['filesize']) 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) # 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()
欢迎转载,但要标明出处.否则追究.欢迎大家阅读收藏和评论,会更新很多精粹。

浙公网安备 33010602011771号