server端:
import queue
import socket
import json
import struct
import time
buffer=1024
import os
q2=queue.Queue()
file_path=os.path.join(os.getcwd(),'test.json')
with open(file_path,'r') as f:
data_json=json.load(f)
q2.put(data_json)
f.close()
q2.put('{"a":2,"b":2,"d":1212121}')
q2.put('{"a":3,"b":2}')
q2.put('{"a":5,"b":2}')
q2.put('{"a":5,"b":2}')
sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sk.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1)
sk.bind(('127.0.0.1', 44455))
sk.listen(1)
conn, addr = sk.accept()
while True:
if not q2.empty():
data_str = q2.get()
print('发送data_str')
json_data = json.dumps(data_str) # 字典转成了字符串
byte_data = json_data.encode('utf-8') # 字符串转成了bytes
data_len = len(byte_data) # 报头的长度
pack_len = struct.pack('i', data_len)
print(pack_len)
conn.send(pack_len) # 先发报头的长度
# conn.send(byte_data)
i = 0
while data_len > 0:
print(data_len)
if data_len >= buffer:
content = byte_data[i * buffer:(i + 1) * buffer]
conn.send(content)
data_len -= buffer
i += 1
else:
content = byte_data[i * buffer:]
conn.send(content)
data_len = 0
break
# conn.close()
# sk.close()
client端:
import socket
import struct
sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sk.connect(('127.0.0.1',44455))
# 接收文件
buffer=1024
while True:
pack_len=sk.recv(4) # 报头长度
print(pack_len)
if pack_len:
data_len=struct.unpack('i',pack_len)[0]
print(data_len)
# data = sk.recv(data_len).decode('utf-8')
# print(data)
content = b''
while data_len>0:
print(data_len)
if data_len >= buffer:
content_temp = sk.recv(buffer)
content += content_temp
data_len -= buffer
else:
content_temp = sk.recv(data_len)
content += content_temp
data_len = 0
break
print(content.decode('utf-8'))