Question HTTPListener

ross246

Member
Joined
Oct 19, 2010
Messages
6
Programming Experience
Beginner
Hi

I am creating an application that simply responds with a string to certain HTTP GET/POST requests using an HttpListener. There is a total of about 90 clients sending requests. My application seems to work, but I would like to know if there is anything I am missing in terms of best practices or possible memory leaks. I tried using the asynchronous method but I struggled and didn't quite understand it so I chose to stick with something I can understand. Here is the code for my server class which gets instantiated from my main form

VB.NET:
Dim bStarted As Boolean = False
    Dim bAcceptConn As Boolean = False
    Dim listener As System.Net.HttpListener

    Public Sub StartServer()
        Try
            listener = New HttpListener
            listener.Prefixes.Add("http://*:" & My.Settings.lPort & "/")
            listener.Start()
            bStarted = True
            bAcceptConn = True
            Dim thListener As New Threading.Thread(AddressOf ProcessRequests)
            thListener.Start()
        Catch e As Exception
            ' Log error here
        End Try
    End Sub

    Public Sub ProcessRequests()
        Dim context As HttpListenerContext
        While bStarted
            context = listener.GetContext
            If context.Request.RawUrl.ToLower = "/kill" And IPAddress.IsLoopback(context.Request.RemoteEndPoint.Address) Then
                bStarted = False
                Exit While
            Else
                System.Threading.ThreadPool.QueueUserWorkItem(New System.Threading.WaitCallback(AddressOf ProcessClient), context)
            End If
        End While
        listener.Stop()
        listener = Nothing
    End Sub

    Public Sub ProcessClient(ByVal context As HttpListenerContext)
            If bAcceptConn Then
                    Dim hClient As New HandleClient(context)
                    hClient.ProcessClient()
                    'HandleClient class will take context and create a response to send from within the HandleClient class
            End If
    End Sub

Do I need to explicitly dispose of hClient (HandleClient) or will the GC do this for me once its thread runs its course? What limitations would I face using this method in comparison to the asynchronous method?

Kind Regards
Ross
 
Back
Top