标签:div user col 大小 listen 服务端 decode 考试 字符串
客户端client:
1 import os 2 import json 3 import socket 4 import struct 5 6 sk = socket.socket() 7 sk.connect((‘127.0.0.1‘,8090)) 8 9 buffer = 1024 10 11 head = {‘filepath‘:r‘/Users/mango/Downloads/试题/07 python fullstack s9day9 第一次考试试题讲解‘, 12 ‘filename‘:r‘07 python fullstack s9day9 第一次考试试题讲解.mp4‘, 13 ‘filesize‘:None} #报头 14 file_path = os.path.join(head[‘filepath‘],head[‘filename‘]) #文件路径 15 filesize = os.path.getsize(file_path) #文件大小 16 head[‘filesize‘] = filesize 17 18 json_head = json.dumps(head) #字典转字符串 19 bytes_head = json_head.encode(‘utf-8‘) #字符串转bytes 20 head_len = len(bytes_head) #计算报头的bytes有多长 21 struct_len = struct.pack(‘i‘,head_len) #打包成固定的4个字节 22 sk.send(struct_len) #发送长度 23 sk.send(bytes_head) #发送报头 24 with open(file_path,‘rb‘)as f: #打开文件 25 while filesize: 26 if filesize >= buffer: 27 content = f.read(buffer) 28 filesize -= buffer 29 sk.send(content) 30 else: 31 f.read(filesize) 32 filesize -= buffer 33 sk.send(content) 34 sk.close()#
服务端server:
1 import socket 2 import struct 3 import json 4 5 sk = socket.socket() 6 sk.bind((‘127.0.0.1‘,8090)) 7 sk.listen() 8 buffer = 1024 9 conn,addr = sk.accept() 10 11 head_len = conn.recv(4) 12 head_len = struct.unpack(‘i‘,head_len)[0] 13 json_head = conn.recv(head_len).decode(‘utf-8‘) 14 head = json.loads(json_head) # 报头 15 filesize = head[‘filesize‘] 16 with open(head[‘filename‘],‘wb‘)as f: 17 while filesize: 18 if filesize >= buffer: 19 content = conn.recv(buffer) 20 f.write(content) 21 filesize -= buffer 22 else: 23 content = conn.recv(filesize) 24 f.write(content) 25 break 26 conn.close() 27 sk.close()
标签:div user col 大小 listen 服务端 decode 考试 字符串
原文地址:https://www.cnblogs.com/Jeery/p/10488477.html