问题描述:

I'm new to to socket programming and TCP communication and I'm working on an application that should receive requests (website urls) from a computer that has access to a server but no internet connection, then it should send the website to the client as a response. So far I have been able to listen to requests successfully but when I try to send the response the browsers hangs.

 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();

What exactly am I doing wrong and how can I fix this (send responses back to the client) ?

网友答案:

If you want to write an HTTP proxy, you must follow every requirement for proxies in the HTTP specification. For example:

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.

and:

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).

and:

  • 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).

An HTTP proxy is an incredibly complex beast and possibly the worst possible choice for someone who isn't experienced in writing networking code.

相关阅读:
Top