文件断点续传
服务端
from socket import * import struct import json import time import os ip_port = ("127.0.0.1",8080) server = socket(AF_INET,SOCK_STREAM) server.bind(ip_port) server.listen(5) while True: conn,client_addr = server.accept() while True: head_size = struct.unpack("i",conn.recv(4))[0] head_bytes = conn.recv(head_size) head_dic = json.loads(head_bytes.decode(("utf-8"))) file_name = head_dic.get("file_name") file_size = head_dic.get("file_size") recv_size = 0 if os.path.exists(file_name): recv_size = os.path.getsize(file_name) recv_size_str = str(recv_size) conn.send(struct.pack("i",len(recv_size_str))) conn.send(recv_size_str.encode("utf-8")) start = time.time() with open(file_name,"ab") as f: while recv_size < file_size: data = conn.recv(2048) recv_size += len(data) f.write(data) f.flush() if time.time() - start >= 1: msg = "文件上传进度:%s%%"%str((100*recv_size//file_size)) # print(msg) conn.send(msg.encode("utf-8")) start = time.time() msg = "文件上传进度:100%,文件上传成功!" conn.send(msg.encode("utf-8")) # print(msg) break conn.close() server.close()
客户端
from socket import * from threading import Thread import json import struct import os def recv(client): while True: try: msg = client.recv(1024) if not msg:break print(msg.decode("utf-8")) except Exception: break if __name__ == '__main__': ip_port = ("127.0.0.1",8080) client = socket(AF_INET,SOCK_STREAM) client.connect(ip_port) file_path = r"" # <<<<<<< 此处需填入上传文件的路径 file_name = os.path.basename(file_path) file_size = os.path.getsize(file_path) head_dic = { "file_name":file_name, "file_size":file_size, } head_bytes = json.dumps(head_dic).encode("utf-8") client.send(struct.pack("i",len(head_bytes))) client.send(head_bytes) str_size = struct.unpack("i",client.recv(4))[0] send_size = int(client.recv(str_size)) with open(file_path,"rb") as f: f.seek(send_size,0) recv_thread = Thread(target=recv,args=(client,)) recv_thread.start() for line in f: client.send(line) recv_thread.join() client.close()