« Home | Diagnosing "Serious Errors" with Windows Memory Di... » | SQL Replication and Renamed Imaged Servers » | IE7: Flickr tag search in the Search bar » | Embedding a Google Map » | New Application/User Settings Interface in VS2005 » | Using HttpListener Asynchronously » | Using HttpListener For X10 Web Interface » | Might We Suggest the Enemy? » | Rebooting the Cable Modem Programmatically Using X... » | VB.NET CM17A X10 Library From Scratch » 

Thursday, December 15, 2005 

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), _
listener)
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.
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 _
Me.ProcessRequest), listener) End Sub
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.

    Add to Google

    This page is powered by Blogger.



Photostream

    www.flickr.com
    justinhenry's photos More of justinhenry's photos