我有一个简单的 C# Windows 服务,它应该对端口 8080 上的 GET 请求响应“OK”。一切正常,只有一个简单的痒......
对服务发出的每个请求都停留在 TIME_WAIT 中。我是否遗漏了什么,我环顾四周,我在 HTTPListeners 和 Windows 服务上看到的大多数示例都以类似的方式进行操作?!
private HttpListener _listener;
protected override void OnStart(string[] args)
{
_listener = new HttpListener();
_listener.Prefixes.Add("http://*:8080/");
_listener.Start();
_listener.BeginGetContext(new AsyncCallback(OnRequestReceive), _listener);
}
protected override void OnStop()
{
_listener.Stop();
}
private void OnRequestReceive(IAsyncResult result)
{
if (!_listener.IsListening)
return;
//Get context for a request.
HttpListenerContext context = _listener.EndGetContext(result);
HttpListenerRequest request = context.Request;
//Obtain a response object.
HttpListenerResponse response = context.Response;
response.ContentType = "application/json";
response.KeepAlive = false;
//Our return message...
string responseString = "OK";
//Construct the response.
byte[] buffer = Encoding.UTF8.GetBytes(responseString);
Stream output = response.OutputStream;
response.ContentLength64 = buffer.Length;
output.Write(buffer, 0, buffer.Length);
//Close and send response
try
{
output.Flush();
output.Close();
response.Close();
}
finally
{
//Wait for another request
_listener.BeginGetContext(new AsyncCallback(OnRequestReceive), _listener);
}
}
编辑:修复了 _listener 的本地声明。