文件上传与下载
服务端
import socket,struct,json server = socket.socket() server.bind(("127.0.0.1",3333)) server.listen(5) while True: client,addr = server.accept() while True: try: ml = client.recv(1024).decode("utf-8")#模拟客户端请求报告 if not ml: client.close() break if ml != "1":continue #开始资质表头 filename = "总结" #计算文件bytes长度 file_len = 0 f = open(r"F:Python_exeday34上午总结","rb") for line in f: line_len = len(line) file_len += line_len f.close() file_dict = {"filename":filename,"length":file_len} #将字典装换为json格式 json_dict = json.dumps(file_dict) #再json字符串转为bytes byte_dict = json_dict.encode("utf-8") #计算字典二进制的长度 head_len = len(byte_dict) #将长度打包成一个数据头 head = struct.pack("i", head_len) client.send(head) client.send(byte_dict) #标记内容完成 #传输正式内容 with open(r"F:Python_exeday34上午总结","rb") as f: for line in f: client.send(line) except ConnectionResetError: print("连接错误连接") client.close() break
客户端
import socket,struct,json client = socket.socket() client.connect(("127.0.0.1",3333)) while True: ml = input(">>>:") if not ml:continue client.send(ml.encode("utf-8")) #获取字典的二进制 bytes_len = client.recv(4) #还原 head_len =struct.unpack('i', bytes_len)[0] #获取数据报头 bytes_dict = client.recv(head_len) #将bytes类型转化为json格式 json_dict = bytes_dict.decode("utf-8") #将字典json格式还原为成python的字典 file_dict=json.loads(json_dict) #获取文件的名称 filename = file_dict["filename"] #获取文件的传输长度 file_len = file_dict["length"] #打开文件追加写 f = open(filename,"ab") #当前接受长度 data_len = 0 while data_len<file_len: data = client.recv(1024) data_len += len(data) f.write(data) f.close() client.close() client.close()
时间服务器
import time import socket server = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) server.bind(("127.0.0.1",4444)) while True: req,addr = server.recvfrom(1024) if not req: fmt = "%Y-%m-%d %X" else: fmt = req.decode("utf-8") back_msg = time.strftime(fmt) server.sendto(back_msg.encode("utf-8"),addr) server.close()
服务端
import socket client = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) while True: time_fmt = input("请输入时间格式 %Y %m %d等") client.sendto(time_fmt.encode("utf-8"),("127.0.0.1",4444)) time,addr = client.recvfrom(1024) print(time.decode("utf-8"))
客户端