套接字循环读写

Socket read and write in a loop

我想在无限循环中读写套接字。

当我在第一个循环中向流写入请求时,我可以立即读取响应。

但对于其他循环 networkStream.DataAvailable 总是 false.

如何连续读取和写入套接字。

    static void ReadWriteSocket()
    {
        string requestString = "GET /WebApplication.UI HTTP/1.1 \r\n" +
                               "Host: 172.17.107.30 \r\n" +
                               "Connection:close \r\n\r\n";

        client = new TcpClient();
        client.Connect(new IPEndPoint(IPAddress.Parse("172.17.107.30"), 80));

        byte[] buffer = System.Text.Encoding.Default.GetBytes(requestString);
        byte[] readBuffer = new byte[1024];

        using (MemoryStream ms = new MemoryStream())
        {
            while (true)
            {
                var networkStream = client.GetStream();

                networkStream.Write(buffer, 0, buffer.Length);

                networkStream.Flush();

                int recievedByte = 0;

                if (networkStream.DataAvailable)
                {
                    while ((recievedByte = networkStream.Read(readBuffer, 0, readBuffer.Length)) > 0)
                    {
                        ms.Write(readBuffer, 0, recievedByte);
                    }
                }
                Console.WriteLine(System.Text.Encoding.Default.GetString(ms.ToArray()));
            }
        }
    }

终于找到漏洞了

TCP 连接被 http header Connection:close

关闭

所以服务器没有响应我的新请求。

我将相应的 header 更改为 连接:keep-alive

谢谢。