TcpListener读取请求返回-1

时间:2016-03-26 22:16:28

标签: c# tcplistener

我这样使用TcpListener

TcpListener _listener;

public void Start()
{
    _listener = new TcpListener(IPAddress.Any, 8000);
    _listener.Start();
    _listener.BeginAcceptSocket(this.HandleAcceptTcpClient, _listener);
}

private void HandleAcceptTcpClient(IAsyncResult result)
{
    TcpClient client = _listener.EndAcceptTcpClient(result);
    _listener.BeginAcceptTcpClient(HandleAcceptTcpClient, _listener);

    Console.WriteLine("Accepting connection...");

    NetworkStream stream = client.GetStream();

    using (StreamWriter writer = new StreamWriter(stream, Encoding.ASCII))
    using (StreamReader reader = new StreamReader(stream, Encoding.ASCII))
    {
        char c;
        while ((c = (char)reader.Read()) != 0)
        {
            Console.Write(c);
        }
        Console.WriteLine();
    }
}

当我向Chrome中的localhost:8000发出请求时,我在控制台中的以下回复(?是无穷无尽的):

enter image description here

当我将HandleAcceptTcpClient内的代码更改为此时(将其更改为打印整数而不是字符):

private void HandleAcceptTcpClient(IAsyncResult result)
{
    TcpClient client = _listener.EndAcceptTcpClient(result);
    _listener.BeginAcceptTcpClient(HandleAcceptTcpClient, _listener);

    Console.WriteLine("Accepting connection...");

    NetworkStream stream = client.GetStream();

    using (StreamWriter writer = new StreamWriter(stream, Encoding.ASCII))
    using (StreamReader reader = new StreamReader(stream, Encoding.ASCII))
    {
        // the changes are on the next 5 lines
        int i;
        while ((i = reader.Read()) != 0)
        {
            Console.Write(i);
        }
        Console.WriteLine();
    }
}

我得到以下内容:

enter image description here

基本上,浏览器似乎正在发出另一个请求并仅发送-1;同样,做reader.ReadToEnd()只是挂起,这意味着它是无止境的。

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

Chrome不会发送其他请求。似乎是Stream.ReadByte方法返回-1,因为它到达流的末尾。

MSDN

  

返回值:转换为Int32的无符号字节,或   如果在流的末尾,则为-1。

因此,如果StreamReader使用输入流的Stream.ReadByte方法从中读取数据,则输出是有意义的。