1

我在 python 中的套接字有问题。

我有一个 TCP 服务器和客户端,它们在while 1循环中相互发送数据。

struct.pack("hh", mousex, mousey)它在 struct 模块 ( )中打包了 2 个短裤。但有时在recv另一台计算机上读取数据时,似乎有 2 条消息粘在一起。这是nagle的算法吗?

在此处输入图像描述

这里到底发生了什么?提前致谢。

4

3 回答 3

1

我同意其他海报的观点,即“TCP 就是这样做的”。TCP保证您的字节以正确的顺序到达,但不保证它们到达的块的大小。我要补充一点,TCP还允许将单个发送拆分为多个recv,甚至例如拆分aabb, ccdd 转换为 aab、bcc、dd。

我整理了这个模块来处理python中的相关问题: http://stromberg.dnsalias.org/~strombrg/bufsock.html 它是在开源许可下,归UCI所有。它已经在 CPython 2.x、CPython 3.x、Pypy 和 Jython 上进行了测试。

高温高压

于 2012-05-07T03:49:01.017 回答
1

可以肯定的是,我必须查看实际的代码,但听起来您希望一个字节始终sendn字节的形式出现在接收器上n,每次。

TCP 流不是这样工作的。它是一种“流”协议,与 UDP 或STCPRDS之类的“数据报”(面向记录)相反。

对于固定数据大小的协议(或任何可以预先预测下一个块大小的协议),您可以在流套接字上构建自己的“类似数据报的接收器”,只需recv()在循环中进行 ing,直到您获得准确的n字节:

def recv_n_bytes(socket, n):
    "attempt to receive exactly n bytes; return what we got"
    data = []
    while True:
        have = sum(len(x) for x in data)
        if have >= n:
            break
        want = n - have
        got = socket.recv(want)
        if got == '':
            break
    return ''.join(data)

(未经测试;python 2.x 代码;不一定高效;等等)。

于 2012-05-07T03:04:27.653 回答
0

You may not assume that data will become available for reading from the local socket in the same size pieces it was provided for sending at the other source end. As you have seen, this might sometimes be usually true, but by no means reliably so. Rather, what TCP guarantees is that what goes in one end will eventually come out the other, in order without anything missing or if that cannot be achieved by means built into the protocol such as retries, then whole thing will break with an error.

Nagle is one possible cause, but not the only one.

于 2012-05-07T02:51:43.817 回答