文件传输, socketserver模块
一. 文件传输
# ===================================== 服务器端 ===================================== # 思路: 做一个要穿的内容的字典, 计算字典的长度, 然后发送字典的长度和字典的json的字符串, 再发送内容 import struct import socket import json import hashlib sock=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<filesize: data=conn.recv(1024) recv_data_length+=len(data) f.write(data) # MD5摘要 md5.update(data) print("文件总大小:%s,已成功接收%s"%(filesize,recv_data_length)) print("接收成功!") conn.send(b"OK") print(md5.hexdigest()) md5_val=md5.hexdigest() client_md5=conn.recv(1024).decode("utf8") if md5_val==client_md5: conn.send(b"203") else: conn.send(b"204") # ===================================== 客户端 ===================================== import socket import os import json import struct import hashlib sock=socket.socket() sock.connect(("127.0.0.1",8800)) while 1 : cmd=input("请输入命令:") # put 111.jpg action,filename=cmd.strip().split(" ") filesize=os.path.getsize(filename) file_info={ "action": action, "filename": filename, "filesize": filesize, } file_info_json=json.dumps(file_info).encode("utf8") ret=struct.pack("i",len(file_info_json)) # 发送 file_info_json的打包长度 sock.send(ret) # 发送 file_info_json字节串 sock.send(file_info_json) # 发送 文件数据 md5=hashlib.md5() with open(filename,"rb") as f: for line in f: sock.send(line) md5.update(line) data=sock.recv(1024) print(md5.hexdigest()) md5_val=md5.hexdigest() sock.send(md5_val.encode("utf8")) is_valid=sock.recv(1024).decode('utf8') if is_valid=="203": print("文件完整!") else: print("文件上传失败!")
二. socketserver模块
import socketserver class 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()