title: Handling multiple requests with C# HttpListener
body: <p>I have a .NET Windows Service which spawns a thread that basically just acts as an <code>HttpListener</code>. This is working fine in synchronous mode example...</p>
  
  <pre><code>private void CreateLListener()
  {
      HttpListenerContext context = null;
      HttpListener listener = new HttpListener();
      bool listen = true;
  
      while(listen)
      {
          try
          {
              context = listener.GetContext();
          }
          catch (...)
          {
              listen = false;
          }
          // process request and make response
      }
  }
  </code></pre>
  
  <p>The problem I now have is I need this to work with multiple requests and have them responded to simultaneously or at least in an overlapped way.</p>
  
  <p>To explain further - the client is a media player app which starts by making a request for a media file with the request header property <code>Range bytes=0-</code>. As far as I can tell it does this to work out what the media container is.</p>
  
  <p>After it has read a 'chunk' (or if it has read enough to ascertain media type) it then makes another request (from a different client socket number) with <code>Range bytes=X-Y</code>. In this case Y is the Content-Length returned in the first response and X is 250000 bytes less than that (discovered using IIS as a test). At this stage it is getting the last 'chunk' to see if it can get a media time-stamp to gauge length.</p>
  
  <p>Having read that, it makes another request with <code>Range bytes=0-</code> (from another socket number) to start streaming the media file properly.</p>
  
  <p>At any time though, if the user of the client performs a 'skip' operation it then sends another request (from yet another socket number) with <code>Range bytes=Z-</code> where Z is the position to jump to in the media file.</p>
  
  <p>I'm not very good with HTTP stuff but as far as I can tell I need to use multiple threads to handle each request/response while allowing the original <code>HttpListener</code> to return to listening. I've done plenty of searching but can't find a model which seems to fit.</p>
  
  <p><strong>EDIT:</strong></p>
  
  <p>Acknowledgement and gratitude to Rick Strahl for the following example which I was able to adapt to suit my needs...</p>
  
  <p><a href="http://www.west-wind.com/weblog/posts/2005/Dec/04/Add-a-Web-Server-to-your-NET-20-app-with-a-few-lines-of-code" rel="noreferrer">Add a Web Server to your .NET 2.0 app with a few lines of code</a></p>