我花了一些时间来制作Http Server,我决定使用TcpListener
类(之前我使用HttpListener
)。问题是每个浏览器都给我一条消息:“拒绝连接”。这很奇怪,因为浏览器通常会使用内容(在本例中为html页面)和200个代码获取http标头。此外,我看到我的页面大约0.5秒,然后消失。
WebServer ws = new WebServer(SendResponse, address);
Thread thread = new Thread(new ThreadStart(ws.Run));
thread.Start();
WebServer类:
public void Run() {
_listener = new TcpListener(IPAddress.Any, 8080);
_listener.Start();
while(isRunning)
{
TcpClient client = _listener.AcceptTcpClient();
Thread thread = new Thread(() => Connection(client));
thread.Start();
Thread.Sleep(1);
}
}
public void Connection(TcpClient client)
{
NetworkStream stream = client.GetStream();
string response = "HTTP/1.0 200 OK\r\n"
+ "Content-Type: text/html\r\n"
+ "Connection: close\r\n"
+ "\r\n";
byte[] bytesResponse = Encoding.ASCII.GetBytes(response);
byte[] data = Encoding.ASCII.GetBytes("<!doctype html><html><body><h1>test server</h1></body></html>");
stream.Write(bytesResponse, 0, bytesResponse.Length);
stream.Write(data, 0, data.Length);
stream.Dispose();
}
我想这不是防火墙故障,因为另一个C#服务器,例如这个:documentation就像一个魅力。怎么了?
答案 0 :(得分:0)
我找到了问题的答案。
标题Content-Length
丢失了:)