校验文件一致性
#客户端 import socket sk = socket.socket() sk.connect(('127.0.0.1',8802)) import os import hmac u = os.urandom(16) sk.send(u) h = hmac.new(b'alex_sb',u) h = h.digest() sk.send(h) print(sk.recv(1024))
#服务端
import socket sk = socket.socket() sk.bind(('127.0.0.1',8802)) sk.listen(5) conn,_ = sk.accept() u= conn.recv(1024) import os import hmac h = hmac.new(b'alex_sb',u) h= h.digest() recv1 = conn.recv(1024) if recv1 == h: conn.send(b'hello') else: conn.close()
2.实现文件上传和下载,以及socketserver模块
#服务端
import socketserver import struct import json class Myserver(socketserver.BaseRequestHandler): def handle(self): conn = self.request while 1: try: #把字典字节长度接到后用unpack解压字节长度 pack_length = conn.recv(4) length_bytes = struct.unpack('i',pack_length)[0] dic = conn.recv(length_bytes).decode('utf-8') dic_data = json.loads(dic) with open(dic_data['filename'],'wb')as f: while dic_data['filesize'] >0: content = conn.recv(1024) dic_data['filesize'] -= len(content) f.write(content) except Exception as e: break conn.close() print('本次接收完') server = socketserver.ThreadingTCPServer(('127.0.0.1',8090),Myserver) server.serve_forever()
#客户端
import socket import os import json import struct sk = socket.socket() sk.connect(('127.0.0.1',8090)) print('连接成功') filename = os.path.basename(r'D:\python-3阶段\day1\day1\1.wmv') filesize = os.path.getsize(r'D:\python-3阶段\day1\day1\1.wmv') #把文件名,文件大小写成字典 dic = {'filename':filename,'filesize':filesize} #用json序列化化成字符串 dic_json = json.dumps(dic) #转化成字节,并求出字节长度 dic_json_bytes = dic_json.encode('utf-8') json_bytes_length = len(dic_json_bytes) #用pack把数字转化成四字节并发送 length_bytes = struct.pack('i',json_bytes_length) sk.send(length_bytes) sk.send(dic_json_bytes) data_length = 0 with open(r'D:\python-3阶段\day1\day1\1.wmv','rb') as f: while filesize>0: content = f.read(1024) filesize -= 1024 sk.send(content) sk.close()