上下文
有一个简单的自描述 HTTP服务器,可以侦听传入的连接。当我将ip_address:port
放入浏览器时,我应该得到一个包含文本信息的简单HTTP页面。如果服务器接受来自客户端的传入流,解析它并读取标头,它工作正常。
但是我需要在不读取任何传入流的情况下实现相同的功能。所以我隐藏了3行代码:
//inputStream = new BufferedStream(socket.GetStream());
//parseRequest();
//readHeaders();
然后我用命令检查结果:
telnet address port
...它运行正常,服务器返回相同的文本。
但在浏览器中我遇到错误:
无法访问此网站
...并在浏览器的命令行中出现ERROR:
获取http://adress:port net :: ERR_CONNECTION_RESET
问题
如果我无法从客户端读取HTTP请求,如何才能正确获得响应?
代码
public void listen()
{
listener = new TcpListener(adr, port);
listener.Start();
while (is_active)
{
TcpClient s = listener.AcceptTcpClient();
HttpProcessor processor = new HttpProcessor(s, this);
Thread thread = new Thread(new ThreadStart(processor.process));
thread.Start();
Thread.Sleep(1);
}
}
public void process()
{
outputStream = new StreamWriter(new BufferedStream(socket.GetStream()));
try {
//inputStream = new BufferedStream(socket.GetStream());
//parseRequest();
//readHeaders();
handleGETRequest();
}
catch (Exception e)
{
writeFailure();
Library.WriteLog("Exception " + e.ToString());
}
outputStream.Flush();
outputStream = null;
socket.Close();
}
public void handleGETRequest()
{
srv.handleGETRequest(this);
}
public override void handleGETRequest(HttpProcessor p)
{
p.outputStream.WriteLine("HTTP / 1.1 200 OK");
p.outputStream.WriteLine("Content-Type: text/html; charset=UTF-8");
p.outputStream.WriteLine("Transfer-Encoding: chunked");
p.outputStream.WriteLine("Connection: keep-alive");
p.outputStream.WriteLine("Keep-Alive: timeout=2000");
p.outputStream.WriteLine("Cache-Control: max-age=0\n");
p.outputStream.WriteLine("<html>");
p.outputStream.WriteLine("<head><title> 200 Test </title></head>");
p.outputStream.WriteLine("<center><h1> 302 Test2 ");
p.outputStream.WriteLine(Service1.GetData());
p.outputStream.WriteLine("</h1></center>");
p.outputStream.WriteLine("<hr><center> nginx </center>");
p.outputStream.WriteLine("</body>");
p.outputStream.WriteLine("</html>");
}