简体   繁体   English

部分TCP封包遗失

[英]Parts of TCP packet loss

I was writing a TCP server. 我正在写一个TCP服务器。 I works fine on localhost. 我在本地主机上工作正常。 When I deploy it remotely some bytes are lost on their way to the destination. 当我远程部署它时,一些字节在到达目的地的途中丢失了。

I used netcat on localhost and remotely and made a diff of the two outputs and the lost bytes are deterministic. 我在本地主机上和远程使用了netcat,对两个输出进行了比较,丢失的字节是确定的。

So I doubt it is packet loss since it's very unlikely the same packet would get lost. 因此,我怀疑这是数据包丢失,因为同一数据包丢失的可能性很小。

I tried to reduce the size of my writes on the socket to 1000 bytes but I still get this problem. 我试图将套接字上的写操作的大小减少到1000个字节,但仍然遇到此问题。

Are there any common reasons for this kind of errors ? 是否存在此类错误的常见原因?

I could post the code but it's just a socket.send from the Boost asio library. 我可以发布代码,但这只是Boost asio库中的一个socket.send。 I'm not sure the error comes from the code otherwise it would not work on localhost. 我不确定错误是否来自代码,否则它将无法在本地主机上运行。

Thank you in advance for your help 预先感谢您的帮助

When sending data using a socket and function send() it returns the number of bytes actually sent, which may be less than the amount you pass to the function. 使用套接字和函数send()发送数据时,它返回实际发送的字节数,该数目可能少于您传递给函数的字节数。

If you use blocking I/O, sometimes a function like this is used: 如果使用阻塞I / O,则有时会使用如下函数:

ssize_t send_all(int socket, const void *data, size_t len)
{
    while (len > 0)
    {
        ssize_t r = send(socket, data, len, 0);
        if (r < 0)
        { //you could also return -1 on EINTR
            if (errno == EINTR)
                continue;
            else
                return -1;
        }
        len -= r;
        data = (const char*)data + r;
    }
    return len;
}

Since you are using boost::asio , not raw sockets that approach is not useful. 由于您使用的是boost::asio ,因此不是原始套接字,这种方法没有用。 But at the async_send documentation you get exactly what you need: 但是在async_send文档中,您可以确切地获得所需的内容:

The send operation may not transmit all of the data to the peer. 发送操作可能不会将所有数据都发送到对等方。 Consider using the async_write function if you need to ensure that all data is written before the asynchronous operation completes. 如果需要确保在异步操作完成之前已写入所有数据,请考虑使用async_write函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM