服务端代码
import json
import socket
import struct
from socket import SOL_SOCKET, SO_REUSEADDR
server = socket.socket()
server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
server.bind(('127.0.0.1', 8080))
server.listen(5)
while True:
sock, addr = server.accept()
while True:
recv_first = sock.recv(4)
dict_length = struct.unpack('i', recv_first)[0]
real_data = sock.recv(dict_length)
real_dict = json.loads(real_data)
print(real_dict)
data_length = real_dict.get('size')
file_name = real_dict.get('file_name')
recv_size = 0
with open(file_name, 'wb') as f:
while recv_size < data_length:
data = sock.recv(1024)
recv_size += len(data)
f.write(data)
客户端
import json
import socket
import struct
import os
client = socket.socket()
client.connect(('127.0.0.1', 8080))
while True:
data_path = r'/Users/XXXXX/Movies'
movie_name_list = os.listdir(data_path)
for i, j in enumerate(movie_name_list, 1):
print(i, j)
chioce = input('以下选项请选择编号下载: ')
if chioce.isdigit():
chioce = int(chioce)
if chioce in range(1, len(movie_name_list) + 1):
movie_name = movie_name_list[chioce - 1]
print(movie_name)
movie_path = os.path.join(data_path, movie_name)
data_dict = {
'file_name': '古典音乐视频集合.mp4',
'size': os.path.getsize(movie_path),
}
data_json = json.dumps(data_dict)
data_first = struct.pack('i', len(data_json))
client.send(data_first)
client.send(data_json.encode('utf8'))
with open(movie_path, 'rb') as f:
for line in f:
client.send(line)
break
|