TCP 通信:发送响应

TCP Communication: Send Response

我是套接字编程和 TCP 通信的新手,我正在开发一个应用程序,该应用程序应该从可以访问服务器但没有互联网连接的计算机接收请求(网站 url),然后它应该发送网站给客户作为回应。到目前为止,我已经能够成功收听请求,但是当我尝试发送响应时,浏览器挂起。

            IPAddress ipAddress = IPAddress.Parse("127.0.0.1");
            TcpListener listener = new TcpListener(ipAddress, 500);
            listener.Start();
            while (true)
            {
                Socket client = listener.AcceptSocket();
                Console.WriteLine("Connection accepted.");
                var childSocketThread = new Thread(() =>
                {
                    byte[] data = new byte[100];
                    int size = client.Receive(data);
                    Console.WriteLine("Recieved data: ");
                    for (int i = 0; i < size; i++)
                        Console.Write(Convert.ToChar(data[i]));
                    // Reading the website in bytes using WebCLient
                    client.Send(RESPONSE) // Here I call the send
                    client.Close();
                });
                childSocketThread.Start();
            }

            listener.Stop();

我到底做错了什么,我该如何解决这个问题(将响应发送回客户端)?

如果要编写 HTTP 代理,则必须遵循 HTTP specification 中对代理的所有要求。例如:

The proxy server MUST signal persistent connections separately with its clients and the origin servers (or other proxy servers) that it connects to. Each persistent connection applies to only one transport link.

和:

A proxy server MUST NOT establish a HTTP/1.1 persistent connection with an HTTP/1.0 client (but see RFC 2068 [33] for information and discussion of the problems with the Keep-Alive header implemented by many HTTP/1.0 clients).

和:

  • If a proxy receives a request that includes an Expect request- header field with the "100-continue" expectation, and the proxy either knows that the next-hop server complies with HTTP/1.1 or higher, or does not know the HTTP version of the next-hop server, it MUST forward the request, including the Expect header field.
  • If the proxy knows that the version of the next-hop server is HTTP/1.0 or lower, it MUST NOT forward the request, and it MUST respond with a 417 (Expectation Failed) status.
  • Proxies SHOULD maintain a cache recording the HTTP version numbers received from recently-referenced next-hop servers.
  • A proxy MUST NOT forward a 100 (Continue) response if the request message was received from an HTTP/1.0 (or earlier) client and did not include an Expect request-header field with the "100-continue" expectation. This requirement overrides the general rule for forwarding of 1xx responses (see section 10.1).

HTTP 代理是一个极其复杂的野兽,对于没有编写网络代码经验的人来说可能是最糟糕的选择。