首页 > 解决方案 > TCP/IP 数据包丢失和更正在我的代码中不起作用

问题描述

据我了解,tcp/ip 应该更正数据包。但在我的应用程序中似乎并非如此。我有一个 C++ 的服务器和一个 C# 的客户端。数据包丢失非常频繁地发生。我在 C++ 中发送数据为

int sentBytes = send(client_, &tempBuffer[0], 1024, 0);

当我打印出来时sentBytes,我总是得到 1024。我在 C# 中收到这个

        int numBytes = 0;
        Byte footer = Convert.ToByte('c');
        while (footer != Convert.ToByte('e'))
        {
            int readBytes = 0;

            while (readBytes < 1024)
            {
                int readThisLoop = _stream.Read(_buffer, numBytes, 1024);
                readBytes += readThisLoop;
                if (readThisLoop != 1024)
                {
                    throw new RsuTcpConnectionException("cannot read data");
                    return 0;
                }
            }
            footer = _buffer[numBytes + 1024 - FooterSize];
            numBytes += readBytes - FooterSize;
        }

Read我经常在通话中得不到完整的 1024 字节。如果这是正常的,我该如何正确阅读?如果我只是删除if块,那么它会尝试读取但失败并挂起......

标签: c#c++tcp

解决方案


异步性与问题无关。Oguz Ozgul 是正确的。循环直到我得到完整的 1024 字节解决了这个问题


推荐阅读