【发布时间】:2011-05-05 08:57:39
【问题描述】:
我在 C# 中实现了一个异步 http 监听器。
我按照here by Microsoft提供的教程进行操作
发现了另一个教程,我愚蠢地没有加入书签,现在再也找不到了。这意味着我有一些我不会自己编写的代码,但提供的解释是有道理的,所以我遵循了。
现在我面临两个问题:
首先,我必须在每次请求后使用 Listener.Stop() 重新启动侦听器,然后再次调用 StartListening 方法,其次,当我这样做时,我会收到每个请求两次。 该请求确实被发送了两次,但我收到了两次。 但是,当我暂停正在收听的线程约 2 秒时,它不会收到两次。
如果我的解释含糊不清,我很抱歉,但我对我的问题的理解也是如此,我不知道是什么原因造成的。 由于回调方法是大多数事情发生的地方,所以我将发布它,如果您需要更多代码,请告诉我。 任何帮助将不胜感激,因为我真的坚持这个。
public void ListenAsynchronously()
{
if (listener.Prefixes.Count == 0) foreach (string s in prefixes) listener.Prefixes.Add(s);
try
{
listener.Start();
}
catch (Exception e)
{
Logging.logException(e);
}
System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(Listen));
}
private void Listen(object state)
{
while (listener.IsListening)
{
listener.BeginGetContext(new AsyncCallback(ListenerCallback), listener);
listenForNextRequest.WaitOne();
}
}
private void ListenerCallback(IAsyncResult ar)
{
HttpListener httplistener = ar.AsyncState as System.Net.HttpListener;
System.Net.HttpListenerContext context = null;
int requestNumber = System.Threading.Interlocked.Increment(ref requestCounter);
if (httplistener == null) return;
try
{
context = httplistener.EndGetContext(ar);
}
catch(Exception ex)
{
return;
}
finally
{
listenForNextRequest.Set();
}
if (context == null) return;
System.Net.HttpListenerRequest request = context.Request;
if (request.HasEntityBody)
{
using (System.IO.StreamReader sr = new System.IO.StreamReader(request.InputStream, request.ContentEncoding))
{
string requestData = sr.ReadToEnd();
//Stuff I do with the request happens here
}
}
try
{
using (System.Net.HttpListenerResponse response = context.Response)
{
//response stuff happens here
}
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.LongLength;
response.OutputStream.Write(buffer, 0, buffer.Length);
response.Close();
StopListening();
//If I dont set the thread to sleep here, I receive the double requests
System.Threading.Thread.Sleep(2500);
ListenAsynchronously();
}
}
catch (Exception e)
{
}
}
【问题讨论】:
-
不知道是什么调用了这个回调,不知道WaitHandle的listenForNextRequest是怎么用的,ListenAsynchronously做了什么方法,有点猜谜游戏。
-
对不起,我添加了代码
-
您应该将一些有用的调试信息打印到控制台(或记录到文件,如果您愿意)并在此处发布。请指定您用于运行此代码的操作系统及其版本。这样会更简单地尝试帮助您...问候,贾科莫
标签: c# .net http httpclient