我希望我的应用程序在端口8040上侦听http请求。我正在使用下面的代码,这是我从Web上复制的示例。我对它进行结构化的方法的问题是,一旦请求进入并且生成响应,则关闭侦听器并返回任务。如何重构代码以使后续请求保持监听器的活动状态?
Task.Factory.StartNew<bool>(() =>
{
System.Net.HttpListener listener = new System.Net.HttpListener();
listener.Prefixes.Add("http://*:8040/");
listener.Start();
Console.WriteLine("Listening...");
// Note: The GetContext method blocks while waiting for a request.
HttpListenerContext context = listener.GetContext();
HttpListenerRequest request = context.Request;
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Construct a response.
string responseString = "<HTML><BODY> Hello world!</BODY></HTML>";
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
// Get a response stream and write the response to it.
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
// You must close the output stream.
output.Close();
listener.Stop();
return true;
});
答案 0 :(得分:1)
我使用Async方法。我使用 BeginGetContext 来设置回调,因此当它收到请求时会运行RequestCallback方法。
在requestCallback中,我获得了一些关于请求的数据,然后我将一些数据写入响应
最后,我再次运行BeginGetContext,以处理新的请求。
在 Firefox 中,我得到了:
Hello Mozilla / 5.0(Windows NT 10.0; WOW64; rv:45.0)Gecko / 20100101 Firefox / 45.0
在 Chrome 中,我得到了:
Hello Mozilla / 5.0(Windows NT 10.0; WOW64)AppleWebKit / 537.36(KHTML,与Gecko一样)Chrome / 49.0.2623.112 Safari / 537.36
public MainWindow()
{
InitializeComponent();
System.Net.HttpListener listener = new System.Net.HttpListener();
listener.Prefixes.Add("http://localhost:8040/");
listener.Start();
listener.BeginGetContext(RequestCallback, listener);
}
private void RequestCallback(IAsyncResult ar)
{
HttpListener listener = (HttpListener) ar.AsyncState;
var context = listener.EndGetContext(ar);
var userAgent = context.Request.UserAgent;
var responseMsg = "Hello " + userAgent;
var responseMsgBytes = Encoding.UTF8.GetBytes(responseMsg);
context.Response.ContentLength64 = responseMsgBytes.Length; //Response msg size
context.Response.OutputStream.Write(responseMsgBytes,0,responseMsgBytes.Length);
context.Response.OutputStream.Close();
listener.BeginGetContext(RequestCallback, listener); //Enable new requests
}
另请查看this post
我希望这可以帮到你。