标签:forever open load ack bre elf send 服务 enc
# tcp服务端 import socketserver import os import json import struct class MyRequestHandle(socketserver.BaseRequestHandler): def handle(self): while 1: try: recv_data = self.request.recv(1024) if len(recv_data) == 0: break if recv_data.decode(‘utf-8‘) == ‘下载‘: data_size = os.path.getsize(r‘E:\python之路\01 课程\week08-day02\03 课后作业\下载的图片.jpg‘) head_dict = {‘data_size‘: data_size} head_dict_json = json.dumps(head_dict) head_dict_bytes = head_dict_json.encode(‘utf-8‘) tag_4 = struct.pack(‘i‘, len(head_dict_bytes)) self.request.send(tag_4) self.request.send(head_dict_bytes) with open(r‘E:\python之路\01 课程\week08-day02\03 课后作业\下载的图片.jpg‘, ‘rb‘)as f: for line in f: self.request.send(line) except Exception as e: print(e) break self.request.close() s = socketserver.ThreadingTCPServer((‘127.0.0.1‘, 3001), MyRequestHandle) s.serve_forever()
# tcp客户端 import socket import os import json import struct client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client.connect((‘127.0.0.1‘, 3001)) while 1: send_data = input(‘上传or下载:‘).strip() if len(send_data) == 0: continue client.send(send_data.encode(‘utf-8‘)) if send_data == ‘下载‘: tag_4 = client.recv(4) head_dict_len = struct.unpack(‘i‘, tag_4)[0] head_dict_bytes = client.recv(head_dict_len) head_dict_json = head_dict_bytes.decode(‘utf-8‘) head_dict = json.loads(head_dict_json) data_size = head_dict.get(‘data_size‘) recv_size = 0 file_path = os.path.join(r‘E:\python之路\01 课程\week08-day02\05 下载区‘, r‘下载的图片.jpg‘) with open(r‘{}‘.format(file_path), ‘wb‘)as f: while recv_size < data_size: recv_data = client.recv(1024) f.write(recv_data) recv_size += len(recv_data)
标签:forever open load ack bre elf send 服务 enc
原文地址:https://www.cnblogs.com/caoyu080202201/p/12749543.html