【发布时间】:2015-04-01 03:21:07
【问题描述】:
在我构建的应用程序中,需要可以同时为多个客户端提供服务的网络服务器。
为此,我使用 HttpListener 对象。及其Async方法\事件BeginGetContext和EndGetContext。
在委托的方法中,有一个调用让监听器重新开始监听,并且它起作用了..主要是。
提供的代码是我在这里和那里找到的代码的混合,以及延迟,以模拟数据处理瓶颈。
问题是,它仅在提供最后一个连接后才开始管理下一个连接.. 对我没有用。
public class HtServer {
public void startServer(){
HttpListener HL = new HttpListener();
HL.Prefixes.Add("http://127.0.0.1:800/");
HL.Start();
IAsyncResult HLC = HL.BeginGetContext(new AsyncCallback(clientConnection),HL);
}
public void clientConnection(IAsyncResult res){
HttpListener listener = (HttpListener)res.AsyncState;
HttpListenerContext context = listener.EndGetContext(res);
HttpListenerRequest request = context.Request;
// Obtain a response object.
HttpListenerResponse response = context.Response;
// Construct a response.
// add a delay to simulate data process
String before_wait = String.Format("{0}", DateTime.Now);
Thread.Sleep(4000);
String after_wait = String.Format("{0}", DateTime.Now);
string responseString = "<HTML><BODY> BW: " + before_wait + "<br />AW:" + after_wait + "</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;
// You must close the output stream.
output.Write(buffer, 0, buffer.Length);
output.Close();
listener.BeginGetContext(new AsyncCallback(clientConnection), listener);
}
}
编辑
private static void OnContext(IAsyncResult ar)
{
var ctx = _listener.EndGetContext(ar);
_listener.BeginGetContext(OnContext, null);
Console.WriteLine(DateTime.UtcNow.ToString("HH:mm:ss.fff") + " Handling request");
var buf = Encoding.ASCII.GetBytes("Hello world");
ctx.Response.ContentType = "text/plain";
// prevent thread from exiting.
Thread.Sleep(3000);
// moved these lines here.. to simulate process delay
ctx.Response.OutputStream.Write(buf, 0, buf.Length);
ctx.Response.OutputStream.Close();
Console.WriteLine(DateTime.UtcNow.ToString("HH:mm:ss.fff") + " completed");
}
输出是
【问题讨论】:
标签: c# asynchronous httplistener