一. 文件传输
# ===================================== 服务器端 ===================================== # 思路: 做一个要穿的内容的字典, 计算字典的长度, 然后发送字典的长度和字典的json的字符串, 再发送内容import structimport socketimport jsonimport hashlibsock=socket.socket()sock.bind(('127.0.0.1',8800))sock.listen(5)while 1: print("server is working....") conn,addr= sock.accept() while 1: # 接收json的打包长度 file_info_length_pack=conn.recv(4) file_info_length=struct.unpack("i",file_info_length_pack)[0] # 接收json字符串 file_info_json=conn.recv(file_info_length).decode("utf8") file_info=json.loads(file_info_json) action=file_info.get("action") filename=file_info.get("filename") filesize=file_info.get("filesize") # 循环接收文件 md5=hashlib.md5() with open("put/"+filename,"wb") as f: recv_data_length=0 while recv_data_length
二. socketserver模块
import socketserverclass Myserver(socketserver.BaseRequestHandler): def handle(self): # 字节类型 while 1: # 针对window系统 try: print("等待信息") data = self.request.recv(1024) # 阻塞 # 针对linux if len(data) == 0: break if data == b'exit': break response = data + b'SB' self.request.send(response) except Exception as e: break self.request.close()# 1 创建socket对象 2 self.socket.bind() 3 self.socket.listen(5)server=socketserver.ForkingUDPServer(("127.0.0.1",8899),Myserver)server.serve_forever()