.net - 从网络流中读取 : packet fragmentation

标签 .net tcp tcpclient networkstream fragmentation

我有一台服务器通过 NetworkStream.Read 管理两个客户端。

应用协议(protocol)是:

ClientMessage [128 Bytes] → 来自服务器的响应 [128 Bytes]

现在在服务器端:MyTcpClient.GetStream().Read() 是否可能只返回 < 128 字节,尽管来自客户端的所有消息都正好是 128 字节长?

我猜这样的客户端消息足够短,可以放入 tcp/ip 层上的一个数据包中 - 但是会不会有某种碎片或随机性呢?

NetworkStream.DataAvailable 是防御此问题的正确属性吗?

在顺利运行数小时后,我有时会遇到奇怪的错误和连接丢失,这指向类似的事情。

提前致谢。

最佳答案

Is it possible, that MyTcpClient.GetStream().Read() returns only < 128 Bytes

是的。您不能假设对 Read() 的调用将返回 128 个字节。

参见 docs :

The total number of bytes read into the buffer. This can be less than the number of bytes requested if that many bytes are not currently available, or zero (0) if the end of the stream has been reached.

参见 this有关如何正确读取流的链接

尝试这样的事情:(传入一个 128 字节的数组)

private static void ReadWholeArray (Stream stream, byte[] data)
    {
        int offset=0;
        int remaining = data.Length;
        while (remaining > 0)
        {
            int read = stream.Read(data, offset, remaining);
            if (read <= 0)
                throw new EndOfStreamException 
                    (String.Format("End of stream reached with {0} bytes left to read", remaining));
            remaining -= read;
            offset += read;
        }
    }

关于.net - 从网络流中读取 : packet fragmentation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5446409/

相关文章:

linux - 我用 iptables 设置了 socket MARK 和 TTL,但是我不能从 getsockopt 读取它?

java - 如何从服务器获取客户端套接字的确认?

c# - 如何使用 C# .NET CORE 2.0 将 FIX 登录消息发送到 GDAX

sockets - 如何在应用程序中处理 TCP keepalive

node.js - socket.emit 在一个用 NodeJS 编写的简单 TCP 服务器中?

c# - 有没有办法在 C# 中获取内部类列表?

c# - 异步/等待抛出未处理的异常

.net - 如何在.NET中创建可继承的信号量?

c# - 保存到数据库时字符串被截断

spring - 使用 Spring Integration TCP IP 套接字发送和接收数据