有什么方法可以避免在Python套接字数据传输中丢失字节?

时间:2019-05-27 10:25:50

标签: python node.js sockets

我有两个不同的python客户端通过Internet上的外部节点服务器相互通信(客户端A和客户端B)。客户端A应该在短时间内向客户端B发送许多已标识的消息,节点服务器负责将所有收到的消息从A转发到B。

正在发生的事情是客户端A正在覆盖某些消息。

我在客户端B上检测到问题,在该位置我分析了消息。但是,由于我已经能够在节点服务器日志上看到损坏的消息,因此在客户端A和节点服务器之间的消息传输中会出现问题。

我将显示一些伪代码以及有关错误的日志(仅限客户端A和服务器):

客户A

代码     ...     导入套接字

server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.connect((HOST, PORT))

...

while not END:
    #Prepare message_to_clinet

    #If I uncomment this timer, the error will not appear (or appear later)
    #time.sleep(0.2)

    # I have tried either sendall and send. But it seems that is not effective
    server_socket.sendall(message_to_client)
    print '(Sent):' + message_to_client

记录发生错误的时间 想象一下,我想发送100次消息:“错误在哪里?”

...
(Sent): Where is the bug?
(Sent): Where is the bug?
(Sent): Where is the bug?
(Sent): Where is the bug?
(Sent): Where is the bug?
...

节点

代码

const net = require('net');
const tcpServer = net.createServer(connection.requestHandler);
tcpServer.listen(connection.port, (err) => {
    if (err) {
        return console.log('tcp socket error', err);
    }

    console.log(`tcp socket listening on ${connection.port}`);
});

...

const requestHandler = (sock) => {   
    sock.on('data', (data) => {
        const protocol_message = new Buffer(data).toString('ascii');

        //Send this message to remote client
        currentConnection.sendMessagesToClient(protocol_message)
        console.log('Received: ' + protocol_message)
    }
}

记录发生错误的时间。 我为每个socket.send收到更多消息,可能是因为socket.send在短时间内在客户端A上被多次调用了(这不是问题,因为在实际代码中,我有一个4字节长的前缀以防止读取时出错)在客户B上)

...
Received: Where is the bug? Where is the bug? Where is the bug?  Where is the bug?Where is the bug?
Received: Where is the bug? Where is the bug? Where is the bug?  Where is the bug?Where is the bug?
Received: Where is thWhere is the bug? Where is the bug?Where is the bug?
...

在这里,我看到我重复发送的100条消息之一已损坏。但是,在客户端A上,一切似乎都很好。

有人知道此错误的可能原因吗?

我知道如果在客户端A的每条消息之间放置time.sleep(0.1),该错误将花费更多的时间并发生传输的字节。但是,当它起作用时,它太慢了。 我也知道,如果我使用开发人员本地服务器,则无法重现该错误。我的猜测是这与套接字缓冲区和传输延迟有关。

编辑:我正在使用Python 2.7

2 个答案:

答案 0 :(得分:1)

我找到了解决我问题的答案。基本上,python客户端一切都正确。但是,使用TCP套接字,可以在上层将消息拆分为多个块,这会导致服务器端出现愚蠢的错误,因为我一直在寻找第一个字符来决定将消息重定向到哪个套接字。当然,这根本不是一个好方法,现在它已经解决并且可以工作了。

尽管这是服务器端的错误,但我只是找到它是因为我进行了一些研究,并得出结论,TCP保证相同的顺序,但是它可以将数据拆分成大块。

还是谢谢你!

答案 1 :(得分:0)

您可以随时尝试:

s.recv #insert increased buffer size here#

可能会工作。