NetworkSteam无需写入即可读取

时间:2014-04-23 20:12:14

标签: c# networkstream

所以我正在编写一个应用程序,我需要将数据从客户端传输到我的服务器,并且我已经注意到NetworkStream.Read函数的行为方式有一些非常奇怪的行为。我发送长度约为18个字节的数据包,如果我在服务器中进行while循环读取然后写入,那么我将正确地获取所有数据包。但是,如果我只读取并且从不写入,则在单个数据包之后读取不会返回。相反,它在返回之前收集了几个数据包,说它在每次迭代时收到了大约300多个字节。有人知道我为什么会这样做吗?我可以简单地回复' a'每一次,但这似乎有点贫民区。

以下是代码部分:

    private static void HandleClientComm(object client)
    {
        TcpClient tcpClient = (TcpClient)client;
        NetworkStream clientStream = tcpClient.GetStream();

        byte[] message = new byte[4096];
        int bytesRead;
        int count = 0;
        while (true)
        {
            bytesRead = 0;

            try
            {
                // Block until a client sends a message
                bytesRead = clientStream.Read(message, 0, 4096);
            }
            catch
            {
                // A socket error has occured
                break;
            }

            if (bytesRead == 0)
            {
                // The client has disconnected from the server
                break;
            }

            Debug.print("Number of bytes: {0:D}", bytesRead);
            count++;

            // Message has successfully been received. Echo back.
            clientStream.Write(new byte[2], 0, 1);

        }
        Debug.print("Count: {0:F}", count);

        tcpClient.Close();
    }

0 个答案:

没有答案
相关问题