阅读从网络数据流:数据包碎片 [英] Reading from a network stream: packet fragmentation

查看:135
本文介绍了阅读从网络数据流:数据包碎片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

应用协议是:

ClientMessage [128字节] - >从服务器响应[128字节]

现在@服务器端: 有没有可能,那MyTcpClient.GetStream()读取()只与其中返回。 128字节,虽然是完全128个字节长从客户端的所有邮件?

我想,这样的客户端消息很短,融入了TCP / IP层上的一个包 - 但可能有一些碎片或随机尽管<​​/ P>吗?

时NetworkStream.DataAvailable的权利属性,对这种防御?

顺利几个小时运行后,我有时会莫名其妙的错误和连接的损失,这点类似的东西。

在此先感谢。

解决方案
  

有没有可能,那MyTcpClient.GetStream()读取()只与其中返回。 128字节

是的。你不能假设你调用read()方法将返回128字节。

查看文档

  

读入的字节总数   缓冲区。这可以是小于   如果有很多字节数请求   字节是当前不可用,或   零(0)如果流的端部具有   已经达到。

请参阅如何正确地从流读取此链接

尝试这样的事情,而不是:(通过在一个长度为128字节数组)

 私有静态无效ReadWholeArray(流流,字节[]数据)
    {
        INT偏移= 0;
        诠释剩余= data.Length;
        而(剩余&0)
        {
            INT读= stream.Read(数据,抵消,剩下的);
            如果(读&LT; = 0)
                抛出新EndOfStreamException已
                    (的String.Format(流的末尾达到{0}字节留下来读,其余的));
            剩下的 -  =读取;
            胶印+ =读取;
        }
    }
 

I got a server that is managing two clients through NetworkStream.Read.

Application protocol is:

ClientMessage [128 Bytes] -> Response from Server [128 Bytes]

Now @ server-side: Is it possible, that MyTcpClient.GetStream().Read() returns only < 128 Bytes, although all messages from client-side are exactly 128 bytes long?

I guess that such a client message is short enough to fit into one packet on the tcp/ip layer - but could there be some kind of fragmentation or random although?

Is NetworkStream.DataAvailable the right attribute to defend against this?

After running smoothly for hours, i sometimes get strange errors and connection losses, that point to something like that.

Thanks in advance.

解决方案

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

Yes. You can't assume your call to Read( ) will return 128 bytes.

see the 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.

See this link on how to properly read from streams

Try something like this instead: (pass in a 128 length byte array)

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;
        }
    }

这篇关于阅读从网络数据流:数据包碎片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆