简体   繁体   English

NetworkStream Sleep()问题

[英]NetworkStream Sleep() issue

I have written a TCP Server, in which number of bytes to read is prefixed in two-bytes header. 我已经编写了一个TCP服务器,其中要读取的字节数在两个字节的标头中带有前缀。 After reading from the stream and sending the response back to the client, both NetworkStream and TcpClient are disposed. 从流中读取并将响应发送回客户端之后,将同时处理NetworkStream和TcpClient。 The problem is that the client doesn't seem to receive my response unless I uncomment Thread.Sleep() line. 问题是,除非取消对Thread.Sleep()行的注释,否则客户端似乎不会收到我的响应。 Here is the code: 这是代码:

using (var tcpClient = await tcpServer.AcceptTcpClientAsync())
{
    tcpClient.NoDelay = true;

    using (var stream = tcpClient.GetStream())
    {
        var twoBytesHeader = new TwoByteHeader();
        var headerBuffer = new byte[twoBytesHeader.HeaderLength];

        using (var binaryReader = new BinaryReader(stream, Encoding.ASCII, true))
        {
            headerBuffer = binaryReader.ReadBytes(twoBytesHeader.HeaderLength);

            int newOffset;
            var msgLength = twoBytesHeader.GetMessageLength(headerBuffer, 0, out newOffset);

            var buffer = binaryReader.ReadBytes(msgLength);

            string msgASCII = Encoding.ASCII.GetString(buffer);

            var bufferToSend = await ProcessMessage(msgASCII);

            using (var binaryWriter = new BinaryWriter(stream, Encoding.ASCII, true))
            {
                binaryWriter.Write(bufferToSend);
                binaryWriter.Flush();
            }

            //Thread.Sleep(1000);
        }
    }
}

When Sleep is uncommented, the client receives response and then indicates that client has disconected. 当取消注释睡眠时,客户端会收到响应,然后指示客户端已断开连接。 I can't figure out the reason of this behaviour 我不知道这种现象的原因

You are assuming that a read will read as many bytes as you specified. 您假设读取将读取与指定的字节一样多的字节。 Instead, it will read at least one byte. 相反,它将读取至少一个字节。 Your code needs to be able to deal with that. 您的代码需要能够处理该问题。 BinaryReader.ReadBytes will allow you to read an exact number of bytes and get rid of some of your boilerplate code. BinaryReader.ReadBytes将允许您读取确切数量的字节并摆脱一些样板代码。

Also, you probably should not use ASCII encoding which is the worst possible encoding. 另外,您可能不应该使用ASCII编码,这是最糟糕的编码。

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

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