I implemented an asynchronous HTTP listener in C #.
I followed the tutorial provided here by Microsoft
and found another tutorial, which I stupidly did not bookmark and now can not find again. Bearing in mind that I have code that I would not have written myself, but the explanations provided made sense, so I followed this up.
Now I am faced with two problems:
Firstly, I have to restart the listener after each request with Listener.Stop (), and then call the StartListening method again, and secondly, when I do this, I get each request twice. The request makes net sent twice, but I get it twice. However, it does not get twice when I pause the Thread that I am listening for about 2 seconds.
I apologize if I am very vague in my explanations, but I also understand my problem, I have no idea what causes it. Since the callback method is where most things happen, I will just post it, please tell me if you need any more code. Any help would be greatly appreciated since I was really stuck on this.
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();
}
}
try
{
using (System.Net.HttpListenerResponse response = context.Response)
{
}
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(responseString);
response.ContentLength64 = buffer.LongLength;
response.OutputStream.Write(buffer, 0, buffer.Length);
response.Close();
StopListening();
System.Threading.Thread.Sleep(2500);
ListenAsynchronously();
}
}
catch (Exception e)
{
}
}
source
share