Server.py
import socket;
import json;
import struct;
sk = socket.socket();
sk.bind(('127.0.0.1', 8090));
sk.listen();
buffer = 1024;
conn, addr = sk.accept();
head_len = conn.recv(4);
head_len = struct.unpack('i', head_len)[0];
json_head = conn.recv(head_len).decode('utf-8');
head = json.loads(json_head);
filesize = head['filesize'];
with open(head['filename'], 'wb') as f:
while filesize:
if filesize >= buffer:
content = conn.recv(buffer);
f.write(content);
filesize -= buffer;
else:
content = conn.recv(filesize);
f.write(content);
break;
conn.close();
sk.close();
Client.py
import socket;
import os;
import json;
import struct;
sk = socket.socket();
sk.connect(('127.0.0.1', 8090));
buffer = 1024;
head = {
"filepath": r'c:\video',
"filename": r"video.mp4",
"filesize": None
}
file_path = os.path.join(head['filepath'], head['filename']);
filesize = os.path.getsize(file_path);
head['filesize'] = filesize;
json_head = json.dumps(head); #字典转成字符串
bytes_head = json_head.encode('utf-8'); #字符串转bytes
head_len = len(bytes_head) #报头的长度
pack_len = struct.pack('i', head_len);
# print(head_len, pack_len);
sk.send(pack_len);#先发报头长度
sk.send(bytes_head);#再发送bytes类型的报头
with open(file_path, 'rb') as f:
while filesize:
if filesize >= buffer:
content = f.read(buffer); #每次读出来的内容
sk.send(content);
filesize -= buffer;
else:
content = f.read(buffer);
sk.send(content);
break;
sk.close();