1、server
import socket import json sock=socket.socket() sock.bind(('127.0.0.1',8800)) sock.listen(5) while 1: print("server is working....") conn,addr= sock.accept() while 1: data=conn.recv(1024).decode("utf8") file_info=json.loads(data) print("file_info",file_info) # {'action': 'put', 'filename': '111.jpg', 'filesize': 93605} # 文件信息 action=file_info.get('action') filename=file_info.get('filename') filesize=file_info.get('filesize') conn.send(b"200") # 接收文件数据 with open("put/"+filename,"wb") as f: recv_data_length=0 while recv_data_length<filesize: data=conn.recv(1024) recv_data_length+=len(data) f.write(data) print("文件总大小:%s,已成功接收%s"%(filesize,recv_data_length)) print("接收成功!")
2、client
import socket import os import json sock=socket.socket() sock.connect(("127.0.0.1",8800)) while 1 : cmd=input("请输入命令:") # put 111.jpg action,filename=cmd.strip().split(" ") filesize=os.path.getsize(filename) file_info={ "action": action, "filename": filename, "filesize": filesize, } file_info_json=json.dumps(file_info).encode("utf8") sock.send(file_info_json) # 确认服务端接收到了文件信息 code=sock.recv(1024).decode("utf8") if code=="200": # 发送文件数据 with open(filename,"rb") as f: for line in f: sock.send(line) else: print("服务器异常!")