【问题标题】:python socket connection fail to receive full messagepython套接字连接无法接收完整消息
【发布时间】: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


    【解决方案1】:
      json_data = c.recv(16384).decode() # Increasing this doesn't help
    

    TCP 是流协议而不是消息协议。无法保证如果发送者使用单个 send 发送所有数据,则可以使用单个 recv 接收它们。

    如果对等方仅发送一个 JSON,然后关闭连接,则接收方可能只是简单地 recv 直到没有更多可用数据(recv 返回空消息)并连接各部分:

     data = b''
     while True:
         buf = c.recv(16384)
         if not buf:
             break
         data = data + buf
     json_data = data.decode()
    

    如果相反,对端发送多个“消息”,那么应用程序级别必须有一些消息指示符,例如在每条消息前面加上一个长度(就像在 TLS 中所做的那样),以换行符结束每条消息(就像在SMTP)或类似的。然后接收方需要根据消息格式读取数据,比如先读取长度,再读取给定的字节数。

    【讨论】:

    • 我将采用第一种方法,因为我不想更改发件人数据。现在我怎样才能recv直到它返回空?或者我可以接收直到有一个新的行字符?可以举个例子吗?
    • @NaggappanRamukannan:至于阅读所有内容,请参阅更新后的回复。至于读到行尾见process socket data that ends with a line break
    猜你喜欢
    • 2016-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-04
    • 1970-01-01
    • 2014-06-20
    • 1970-01-01
    相关资源
    最近更新 更多