# 实现一个文件的上传或下载 server端 # 配置文件 ip地址 端口 import socket import struct import json sk = socket.socket() sk.bind(("127.0.0.1", 8090)) sk.listen() buffer = 1024 conn, addr = sk.accept() # 接收 head_length = conn.recv(4) head_length = struct.unpack("i", head_length)[0] json_head = conn.recv(head_length).decode("utf-8") head = json.loads(json_head) # 字典head file_size = head["filesize"] with open("music", "wb") as f: while file_size: if file_size >= buffer: content = conn.recv(buffer) f.write(content) file_size -= buffer else: content = conn.recv(file_size) f.write(content) break conn.close() sk.close() # 发送端(client) import socket import os import json import struct sk = socket.socket() sk.connect(("127.0.0.1", 8090)) buffer = 1024 # 发送文件 head = {"filepath": r"C:Users26651Music", "filename": r"朱七 - 夏天已过去.mp3", "filesize": None} file_path = os.path.join(head["filepath"], head["filename"]) # 文件的路径 file_size = os.path.getsize(file_path) # 文件的大小 head["filesize"] = file_size json_head = json.dumps(head) # 从字典转成字符串 byte_head = json_head.encode("utf-8") # 从字符串转字节 head_length = struct.pack("i", len(byte_head)) # 将报头的长度转化四个字节 sk.send(head_length) sk.send(byte_head) with open(file_path, "rb") as f: while file_size: if file_size >= buffer: content = f.read(buffer) sk.send(content) file_size -= buffer else: content = f.read(file_size) sk.send(content) break sk.close()