一、struct模块
可以把要发送的数据长度转换成固定长度的字节
struct.pack('i',数据长度)
struct.unpack('i',数据长度)
二、上传下载文件作业
server
import struct import socket import json import os sk=socket.socket() sk.bind(('127.0.0.1',8080)) sk.listen() conn,addr=sk.accept() header_len=conn.recv(4) header_len=struct.unpack('i',header_len)[0] header_by=conn.recv(header_len) header=json.loads(header_by) filename=header['filename'] fileside=header['fileside'] buffer=4096 with open(filename,'wb') as f: while fileside: if fileside>=buffer: content=conn.recv(buffer) f.write(content) fileside-=buffer print(fileside) else: content=conn.recv(fileside) break conn.close() sk.close()
client
import struct import socket import json import os sk=socket.socket() sk.connect(('127.0.0.1',8080)) header={'filepath':r'E:人工智能python课件基础班-就业班课件资料 -1-4位基础班 5-14就业班14-人工智能阶段:-机器学习-深度学习-实战项目30-36深度学习' ,'filename':r'对抗生成网络.zip' ,'fileside':None} file_path=os.path.join(header['filepath'],header['filename']) header['fileside']=os.path.getsize(file_path) fileside=header['fileside'] json_header=json.dumps(header).encode('utf-8') header_len=struct.pack('i',len(json_header)) sk.send(header_len)#发送报文的长度 sk.send(json_header)#发送报文 buffer=4096 with open(file_path,'rb') as f: while fileside: if fileside>=buffer: content=f.read(buffer) sk.send(content) fileside-=buffer print(fileside) else: content = f.read(fileside) sk.send(content) break sk.close()