标签:一件事 半连接 struct reading ddr 协议 forever port try
编写cs架构的软件,实现客户端可以下载服务端的文件,如图片、视频、文本等
import socketserver import os import json import struct class MyRequestHandle(socketserver.BaseRequestHandler): def handle(self): # 如果tcp协议,self.request=>conn print(self.client_address) while True: try: file_name = self.request.recv(1024) # 拼接文件路径 dir_name = os.path.dirname(__file__) file_path = os.path.join(dir_name,file_name) # 读取文件,若为空则返回空给客户端 with open(file_path,mode="rb") as f: res = f.read() total_size = len(res) if total_size == 0: res = "None".encode("utf-8") total_size = len(res) file_name = "Error:file has no content!" # 1、制作头 header_dic = { "filename": file_name, "total_size": total_size, "md5": "123123xi12ix12" } json_str = json.dumps(header_dic) json_str_bytes = json_str.encode(‘utf-8‘) # 2、先把头的长度发过去 x = struct.pack(‘i‘, len(json_str_bytes)) self.request.send(x) # 3、发头信息 self.request.send(json_str_bytes) # 4、再发真实的数据 self.request.send(res) except Exception: break self.request.close() # 服务端应该做两件事 # 第一件事:循环地从半连接池中取出链接请求与其建立双向链接,拿到链接对象 s=socketserver.ThreadingTCPServer((‘0.0.0.0‘,8888),MyRequestHandle) s.serve_forever()
from socket import * client=socket(AF_INET,SOCK_STREAM) client.connect((‘39.97.179.91‘,8888)) while True: msg=input(‘请输入需要下载的文件名:‘).strip() if len(msg) == 0:continue client.send(msg.encode(‘utf-8‘)) res=client.recv(1024) print(res.decode(‘utf-8‘))
标签:一件事 半连接 struct reading ddr 协议 forever port try
原文地址:https://www.cnblogs.com/zhubincheng/p/12748862.html