【发布时间】:2018-12-07 08:21:45
【问题描述】:
我使用以下代码接收数据并转储到文件。但是当发送的字符超过 1500 个时,它无法接收到完整的消息,因此 json 在文件中不正确。这种情况不一致发生,即有时会收到完整的消息,有时会失败。
但是如果我们同时使用logstash作为接收器,这个问题就不会发生。
接收脚本:
s.listen(5)
while True:
c, addr = s.accept()
print('Got connection from', addr)
json_data = c.recv(16384).decode() # Increasing this doesn't help
json_dump = json.dumps(json_data)
if os.path.exists(destination_file):
append_write = 'a' # append if already exists
else:
append_write = 'w' # make a new file if not
dump_file = open(destination_file, append_write)
dump_file.write(json_dump + '\n')
dump_file.close()
c.send(b'SUCCESS')
c.close()
发送者脚本
def send_data(socket_conn, data_stream):
try:
json_data = JSONEncoder().encode(data_stream)
json_data = json_data
socket_conn.send(json_data.encode())
socket_conn.send(b'\n')
socket_conn.close()
return True
except socket.error as msg:
logging.error(msg, exc_info=True)
return False
【问题讨论】:
标签: sockets buffer python-sockets