socket文件上传下载
# server
import socket
import json
import struct
import os
sk = socket.socket()
sk.bind(('127.0.0.1',8080))
sk.listed(5)
while True:
conn,addr = sk.accept()
while True:
dic = {'size':os.path.getsize('test.py'),'name':'shabi.py'}
dic_b = bytes(json.dumps(dic),encoding= 'utf8')
dic_b_len = len(dic_b)
obj = struct.pack('i',dic_b_len)
conn.send(obj) # 发送打包好的
conn.send(dic_b)
with open('test.py','rb') as f:
for i in f:
conn.send(i)
conn.close()
sk.close()
# client
import socket
import struct
import json
sk.socket.socket()
sk.connect(('127.0.0.1',8080))
sure = input('开始接收>>>?')
if sure == 'y':
head_len = struct.unpack("i",sk.recv(4))[0]
dic = json.loads(sk.recv(head_len))
l = dic['size']
name = dic['name']
c = 0
data = b''
with open(name,'wb') as f:
while c<l:
if l<1024:
data_in = sk.recv(l)
else:
if l-c>1024:
data_in = sk.recv(1024)
else:
data_in = sk.recv(l-c)
data += data_in
c += len(data_in)
f.write(data)
print(f'{name}文件接收完成!')
else:
print('接收失败!')
sk.close()