Using HttpListener Asynchronously
My previous entry about creating a mini-web server application to take X10 device requests used HttpListener to wait for and respond to HTTP requests synchronously. However, as I develop a user interface for my X10Listener service, I'll need to be able to respond to those requests in the background while the user configures other areas of the service. So I've switched to an asynchronous use of HttpListener. First, in my load subroutine, I start the listener as before, but use BeginGetContext instead of GetContext.
Dim listener As New System.Net.HttpListener listener.Prefixes.Add("http://*:33333/") Try listener.Start() Catch ex As Exception MsgBox(ex.Message) Exit Sub End Try listener.BeginGetContext(New System.AsyncCallback(AddressOf Me.ProcessRequest), _Now I can go on and set up the UI and handle UI events. Note that I pass a reference to the address of another routine called ProcessRequest along with a reference to the listener object. Here is the routine to process the request, which is automatically called when an HTTP request comes in.
listener)
Private Sub ProcessRequest(ByVal result As System.IAsyncResult) Dim listener As Net.HttpListener Dim context As Net.HttpListenerContext listener = result.AsyncState context = listener.EndGetContext(result) ' use context.Request to explore the incoming HTTP request listener.BeginGetContext(New System.AsyncCallback(AddressOf _Note that I never have to instantiate a new HttpListener except during the initial load. I can pass the single listener object around via the asynchronous handler. At the end of the ProcessRequest routine, I simply set up to handle the next incoming request by calling BeginGetContext again. Next, I'll be building the UI and sending a more complex response that will include a configurable, simple HTML menu of X10 commands.
Me.ProcessRequest), listener) End Sub
