Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Asynchronous Event Handling Issue converting code from C# to VB.Net

Posted on 2009-06-29
5
Medium Priority
?
882 Views
Last Modified: 2012-05-07
I found some sample code for hosting a very simple http server service in C# which works well (it's a console app). However, I need to convert this into a VB.Net implementation. I have converted everything fine except for the event handling. In C# the event declaration can be assigned a value (public event EventHandler<HttpRequestEventArgs> IncomingRequest = null;) but in VB it doesn't seem to let me do that directly. I'll paste the working c# code and the *almost* working vb code below. If anyone knows how I should properly wire up the events, please let me know!
//C# CONSOLE APP (MAIN)
 
using System;
using System.IO;
using System.Net;
using System.Text;
 
namespace HttpListenerExample
{
    class Program
    {
        static void Main(string[] args)
        {
            const string ServerTestUrl = "http://localhost:11235/";
            using (WebServer listener = new WebServer(new Uri(ServerTestUrl)))
            {
                listener.IncomingRequest += WebServer_IncomingRequest;
                listener.Start();
                Console.WriteLine("Listener accepting requests: {0}", listener.RunState == WebServer.State.Started);
                Console.WriteLine("Making requests...");
                Console.WriteLine("Press any key to close server.");
                Console.ReadLine();
                listener.Stop();
                listener.Dispose();
            }
        }
 
        public static void WebServer_IncomingRequest(object sender, HttpRequestEventArgs e)
        {
            HttpListenerResponse response = e.RequestContext.Response;
            //string content = DateTime.Now.ToLongTimeString();
            string content = "This is working: " + DateTime.Now.ToShortTimeString();
            byte[] buffer = Encoding.UTF8.GetBytes(content);
            response.StatusCode = (int)HttpStatusCode.OK;
            response.StatusDescription = "OK";
            response.ContentLength64 = buffer.Length;
            response.ContentEncoding = Encoding.UTF8;
            response.OutputStream.Write(buffer, 0, buffer.Length);
            response.OutputStream.Close();
            response.Close();
        }
    }
}
 
//C# WebServer Class
 
using System;
using System.Globalization;
using System.Net;
using System.Threading;
 
namespace HttpListenerExample
{
  public class WebServer : IDisposable
  {
    public event EventHandler<HttpRequestEventArgs> IncomingRequest = null;
 
    public enum State
    {
      Stopped,
      Stopping,
      Starting,
      Started
    }
 
    private Thread _connectionManagerThread = null;
    private bool _disposed = false;
    private HttpListener _listener = null;
    private long _runState = (long)State.Stopped;
 
    public State RunState
    {
      get
      {
        return (State)Interlocked.Read(ref _runState);
      }
    }
 
    public virtual Guid UniqueId { get; private set; }
 
    public virtual Uri Url { get; private set; }
 
    public WebServer(Uri listenerPrefix)
    {
      if (!HttpListener.IsSupported)
      {
        throw new NotSupportedException("The HttpListener class is not supported on this operating system.");
      }
      if(listenerPrefix == null)
      {
        throw new ArgumentNullException("listenerPrefix");
      }
      this.UniqueId = Guid.NewGuid();
      this._listener = new HttpListener();
      this._listener.Prefixes.Add(listenerPrefix.AbsoluteUri);
    }
 
    ~WebServer()
    {
      this.Dispose(false);
    }
 
    private void ConnectionManagerThreadStart()
    {
      Interlocked.Exchange(ref this._runState, (long)State.Starting);
      try
      {
        if (!this._listener.IsListening)
        {
          this._listener.Start();
        }
        if (this._listener.IsListening)
        {
          Interlocked.Exchange(ref this._runState, (long)State.Started);
        }
 
        try
        {
          while (RunState == State.Started)
          {
            HttpListenerContext context = this._listener.GetContext();
            this.RaiseIncomingRequest(context);
          }
        }
        catch (HttpListenerException)
        {
          // This will occur when the listener gets shut down.
          // Just swallow it and move on.
        }
      }
      finally
      {
        Interlocked.Exchange(ref this._runState, (long)State.Stopped);
      }
    }
 
    public virtual void Dispose()
    {
      this.Dispose(true);
      GC.SuppressFinalize(this);
    }
 
    private void Dispose(bool disposing)
    {
      if (this._disposed)
      {
        return;
      }
      if (disposing)
      {
        if (this.RunState != State.Stopped)
        {
          this.Stop();
        }
        if (this._connectionManagerThread != null)
        {
          this._connectionManagerThread.Abort();
          this._connectionManagerThread = null;
        }
      }
      this._disposed = true;
    }
 
    private void RaiseIncomingRequest(HttpListenerContext context)
    {
      HttpRequestEventArgs e = new HttpRequestEventArgs(context);
      try
      {
        if (this.IncomingRequest != null)
        {
          this.IncomingRequest.BeginInvoke(this, e, null, null);
        }
      }
      catch
      {
        // Swallow the exception and/or log it, but you probably don't want to exit
        // just because an incoming request handler failed.
      }
    }
 
    public virtual void Start()
    {
      if (this._connectionManagerThread == null || this._connectionManagerThread.ThreadState == ThreadState.Stopped)
      {
        this._connectionManagerThread = new Thread(new ThreadStart(this.ConnectionManagerThreadStart));
        this._connectionManagerThread.Name = String.Format(CultureInfo.InvariantCulture, "ConnectionManager_{0}", this.UniqueId);
      }
      else if (this._connectionManagerThread.ThreadState == ThreadState.Running)
      {
        throw new ThreadStateException("The request handling process is already running.");
      }
 
      if (this._connectionManagerThread.ThreadState != ThreadState.Unstarted)
      {
        throw new ThreadStateException("The request handling process was not properly initialized so it could not be started.");
      }
      this._connectionManagerThread.Start();
 
      long waitTime = DateTime.Now.Ticks + TimeSpan.TicksPerSecond * 50;
      while (this.RunState != State.Started)
      {
        Thread.Sleep(100);
        if (DateTime.Now.Ticks > waitTime)
        {
          throw new TimeoutException("Unable to start the request handling process.");
        }
      }
    }
 
    public virtual void Stop()
    {
      // Setting the runstate to something other than "started" and
      // stopping the listener should abort the AddIncomingRequestToQueue
      // method and allow the ConnectionManagerThreadStart sequence to
      // end, which sets the RunState to Stopped.
      Interlocked.Exchange(ref this._runState, (long)State.Stopping);
      if (this._listener.IsListening)
      {
        this._listener.Stop();
      }
      long waitTime = DateTime.Now.Ticks + TimeSpan.TicksPerSecond * 10;
      while (this.RunState != State.Stopped)
      {
        Thread.Sleep(100);
        if (DateTime.Now.Ticks > waitTime)
        {
          throw new TimeoutException("Unable to stop the web server process.");
        }
      }
 
      this._connectionManagerThread = null;
    }
  }
  
  public class HttpRequestEventArgs : EventArgs
  {
    public HttpListenerContext RequestContext { get; private set; }
 
    public HttpRequestEventArgs(HttpListenerContext requestContext)
    {
      this.RequestContext = requestContext;
    }
  }
}
 
'VB Console App
 
Imports System
Imports System.IO
Imports System.Net
Imports System.Text
 
Module Module1
 
    Sub Main(ByVal args As String())
        Using listener As WebServer = New WebServer(New Uri("http://localhost:8080/"))
            AddHandler listener.IncomingRequest, New EventHandler(Of HttpRequestEventArgs)(AddressOf WebServer_IncomingRequest)
            listener.Start()
            Console.WriteLine("Listener accepting requests: {0}", (listener.RunState = WebServer.State.Started))
            Console.WriteLine("Making requests...")
            Console.WriteLine("Press any key to close server.")
            Console.ReadLine()
            listener.Stop()
            listener.Dispose()
        End Using
    End Sub
 
    Public Sub WebServer_IncomingRequest(ByVal sender As Object, ByVal e As HttpRequestEventArgs)
        Dim response As HttpListenerResponse = e.RequestContext.Response
        Dim content As String = ("This is working: " & DateTime.Now.ToShortTimeString)
        Dim buffer As Byte() = Encoding.UTF8.GetBytes(content)
        response.StatusCode = 200
        response.StatusDescription = "OK"
        response.ContentLength64 = CLng(buffer.Length)
        response.ContentEncoding = Encoding.UTF8
        response.OutputStream.Write(buffer, 0, buffer.Length)
        response.OutputStream.Close()
        response.Close()
    End Sub
 
End Module
 
'VB WebServer Class
 
Imports System
Imports System.Globalization
Imports System.Net
Imports System.Threading
 
Class WebServer
    Implements IDisposable
    ' Events
    ' Fields
    
    Private _connectionManagerThread As Thread
    Private _disposed As Boolean
    Private _listener As HttpListener
    Private _runState As Long = Long.Parse(State.Stopped)
    Private _UniqueId As Guid
    Private _Url As Uri
 
    Public Enum State
        ' Fields
        Started = 3
        Starting = 2
        Stopped = 0
        Stopping = 1
    End Enum
 
    Public Event IncomingRequest As EventHandler(Of HttpRequestEventArgs)
 
    Dim IncomingRequest As EventHandler(Of HttpRequestEventArgs)
 
    ' Methods
    Public Sub New(ByVal listenerPrefix As Uri)
        If Not HttpListener.IsSupported Then
            Throw New NotSupportedException("The HttpListener class is not supported on this operating system.")
        End If
        If (listenerPrefix Is Nothing) Then
            Throw New ArgumentNullException("listenerPrefix")
        End If
        Me._UniqueId = Guid.NewGuid
        Me._listener = New HttpListener
        Me._listener.Prefixes.Add(listenerPrefix.AbsoluteUri)
    End Sub
 
    Private Sub ConnectionManagerThreadStart()
        Interlocked.Exchange(_runState, Long.Parse(State.Starting))
        Try
            If Not Me._listener.IsListening Then
                Me._listener.Start()
            End If
            If Me._listener.IsListening Then
                Interlocked.Exchange(_runState, Long.Parse(State.Started))
            End If
            Try
                Do While (Me.RunState = State.Started)
                    Dim context As HttpListenerContext = Me._listener.GetContext
                    Me.RaiseIncomingRequest(context)
                Loop
            Catch exception1 As HttpListenerException
            End Try
        Finally
            Interlocked.Exchange(_runState, Long.Parse(State.Stopped))
        End Try
    End Sub
 
    Public Overridable Sub Dispose() Implements IDisposable.Dispose
        Me.Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub
 
    Private Sub Dispose(ByVal disposing As Boolean)
        If Not Me._disposed Then
            If disposing Then
                If (Me.RunState <> State.Stopped) Then
                    Me.Stop()
                End If
                If (Not Me._connectionManagerThread Is Nothing) Then
                    Me._connectionManagerThread.Abort()
                    Me._connectionManagerThread = Nothing
                End If
            End If
            Me._disposed = True
        End If
    End Sub
 
    Protected Overrides Sub Finalize()
        Try
            Me.Dispose(False)
        Finally
            MyBase.Finalize()
        End Try
    End Sub
 
    Private Sub RaiseIncomingRequest(ByVal context As HttpListenerContext)
        Dim e As New HttpRequestEventArgs(context)
        Try
            If Not IncomingRequest Is Nothing Then
                IncomingRequest.BeginInvoke(Me, e, Nothing, Nothing)
            End If
        Catch ex As Exception
        End Try
    End Sub
 
    Public Overridable Sub Start()
        If ((Me._connectionManagerThread Is Nothing) OrElse (Me._connectionManagerThread.ThreadState = ThreadState.Stopped)) Then
            Me._connectionManagerThread = New Thread(New ThreadStart(AddressOf Me.ConnectionManagerThreadStart))
            Me._connectionManagerThread.Name = String.Format(CultureInfo.InvariantCulture, "ConnectionManager_{0}", New Object() {Me.UniqueId})
        ElseIf (Me._connectionManagerThread.ThreadState = ThreadState.Running) Then
            Throw New ThreadStateException("The request handling process is already running.")
        End If
        If (Not Me._connectionManagerThread.ThreadState = ThreadState.Unstarted) Then
            Throw New ThreadStateException("The request handling process was not properly initialized so it could not be started.")
        End If
        Me._connectionManagerThread.Start()
        Dim waitTime As Long = (DateTime.Now.Ticks + TimeSpan.TicksPerSecond * 50)
        Do While (Me.RunState <> State.Started)
            Thread.Sleep(100)
            If (DateTime.Now.Ticks > waitTime) Then
                Throw New TimeoutException("Unable to start the request handling process.")
            End If
        Loop
    End Sub
 
    Public Overridable Sub [Stop]()
        Interlocked.Exchange(_runState, Long.Parse(State.Stopping))
        If Me._listener.IsListening Then
            Me._listener.Stop()
        End If
        Dim waitTime As Long = (DateTime.Now.Ticks + TimeSpan.TicksPerSecond * 10)
        Do While (Me.RunState <> State.Stopped)
            Thread.Sleep(100)
            If (DateTime.Now.Ticks > waitTime) Then
                Throw New TimeoutException("Unable to stop the web server process.")
            End If
        Loop
        Me._connectionManagerThread = Nothing
    End Sub
 
 
    ' Properties
    Public ReadOnly Property RunState() As State
        Get
            Return DirectCast(CInt(Interlocked.Read((Me._runState))), State)
        End Get
    End Property
 
    Overridable Property UniqueId() As Guid
        Get
            Return _UniqueId
        End Get
        Set(ByVal value As Guid)
            _UniqueId = value
        End Set
    End Property
 
    Overridable Property Url() As Uri
        Get
            Return _Url
        End Get
        Set(ByVal value As Uri)
            _Url = value
        End Set
    End Property
 
 
 
    ' Nested Types
 
End Class
 
 
Class HttpRequestEventArgs
    Inherits EventArgs
    ' Methods
    Public Sub New(ByVal requestContext As HttpListenerContext)
        Me.RequestContext = requestContext
    End Sub
 
    Private _RequestContext As HttpListenerContext
 
 
    ' Properties
    Property RequestContext() As HttpListenerContext
        Get
            Return _RequestContext
        End Get
        Set(ByVal value As HttpListenerContext)
            _RequestContext = value
        End Set
    End Property
 
End Class

Open in new window

0
Comment
Question by:tom3030
  • 3
5 Comments
 
LVL 15

Expert Comment

by:mohan_sekar
ID: 24738327
Could you try this?
Imports System
Imports System.IO
Imports System.Net
Imports System.Text

Namespace HttpListenerExample
    Class Program
        Private Shared Sub Main(ByVal args As String())
            Const ServerTestUrl As String = "http://localhost:11235/
            Using listener As New WebServer(New Uri(ServerTestUrl))
                listener.IncomingRequest += WebServer_IncomingRequest
                listener.Start()
                Console.WriteLine("Listener accepting requests: {0}", listener.RunState = WebServer.State.Started)
                Console.WriteLine("Making requests...")
                Console.WriteLine("Press any key to close server.")
                Console.ReadLine()
                listener.[Stop]()
                listener.Dispose()
            End Using
        End Sub
       
        Public Shared Sub WebServer_IncomingRequest(ByVal sender As Object, ByVal e As HttpRequestEventArgs)
            Dim response As HttpListenerResponse = e.RequestContext.Response
            'string content = DateTime.Now.ToLongTimeString();
            Dim content As String = "This is working: " & DateTime.Now.ToShortTimeString()
            Dim buffer As Byte() = Encoding.UTF8.GetBytes(content)
            response.StatusCode = CInt(HttpStatusCode.OK)
            response.StatusDescription = "OK"
            response.ContentLength64 = buffer.Length
            response.ContentEncoding = Encoding.UTF8
            response.OutputStream.Write(buffer, 0, buffer.Length)
            response.OutputStream.Close()
            response.Close()
        End Sub
    End Class
End Namespace


Imports System
Imports System.Globalization
Imports System.Net
Imports System.Threading

Namespace HttpListenerExample
    Public Class WebServer
        Implements IDisposable
        Public Event IncomingRequest As EventHandler(Of HttpRequestEventArgs) = Nothing
       
        Public Enum State
            Stopped
            Stopping
            Starting
            Started
        End Enum
       
        Private _connectionManagerThread As Thread = Nothing
        Private _disposed As Boolean = False
        Private _listener As HttpListener = Nothing
        Private _runState As Long = CLng(State.Stopped)
       
        Public ReadOnly Property RunState() As State
            Get
                Return DirectCast(Interlocked.Read(_runState), State)
            End Get
        End Property
       
Private _UniqueId As Guid
        Public Overridable Property UniqueId() As Guid
            Get
                Return _UniqueId
            End Get
            Private Set(ByVal value As Guid)
                _UniqueId = value
            End Set
        End Property
       
Private _Url As Uri
        Public Overridable Property Url() As Uri
            Get
                Return _Url
            End Get
            Private Set(ByVal value As Uri)
                _Url = value
            End Set
        End Property
       
        Public Sub New(ByVal listenerPrefix As Uri)
            If Not HttpListener.IsSupported Then
                Throw New NotSupportedException("The HttpListener class is not supported on this operating system.")
            End If
            If listenerPrefix Is Nothing Then
                Throw New ArgumentNullException("listenerPrefix")
            End If
            Me.UniqueId = Guid.NewGuid()
            Me._listener = New HttpListener()
            Me._listener.Prefixes.Add(listenerPrefix.AbsoluteUri)
        End Sub
       
        Protected Overrides Sub Finalize()
            Try
                Me.Dispose(False)
            Finally
                MyBase.Finalize()
            End Try
        End Sub
       
        Private Sub ConnectionManagerThreadStart()
            Interlocked.Exchange(Me._runState, CLng(State.Starting))
            Try
                If Not Me._listener.IsListening Then
                    Me._listener.Start()
                End If
                If Me._listener.IsListening Then
                    Interlocked.Exchange(Me._runState, CLng(State.Started))
                End If
               
                Try
                    While RunState = State.Started
                        Dim context As HttpListenerContext = Me._listener.GetContext()
                        Me.RaiseIncomingRequest(context)
                    End While
                Catch generatedExceptionName As HttpListenerException
                    ' This will occur when the listener gets shut down.
                    ' Just swallow it and move on.
                End Try
            Finally
                Interlocked.Exchange(Me._runState, CLng(State.Stopped))
            End Try
        End Sub
       
        Public Overridable Sub Dispose()
            Me.Dispose(True)
            GC.SuppressFinalize(Me)
        End Sub
       
        Private Sub Dispose(ByVal disposing As Boolean)
            If Me._disposed Then
                Exit Sub
            End If
            If disposing Then
                If Me.RunState <> State.Stopped Then
                    Me.[Stop]()
                End If
                If Me._connectionManagerThread IsNot Nothing Then
                    Me._connectionManagerThread.Abort()
                    Me._connectionManagerThread = Nothing
                End If
            End If
            Me._disposed = True
        End Sub
       
        Private Sub RaiseIncomingRequest(ByVal context As HttpListenerContext)
            Dim e As New HttpRequestEventArgs(context)
            Try
                If Me.IncomingRequest IsNot Nothing Then
                    Me.IncomingRequest.BeginInvoke(Me, e, Nothing, Nothing)
                End If
            Catch
                ' Swallow the exception and/or log it, but you probably don't want to exit
                ' just because an incoming request handler failed.
            End Try
        End Sub
       
        Public Overridable Sub Start()
            If Me._connectionManagerThread Is Nothing OrElse Me._connectionManagerThread.ThreadState = ThreadState.Stopped Then
                Me._connectionManagerThread = New Thread(New ThreadStart(Me.ConnectionManagerThreadStart))
                Me._connectionManagerThread.Name = [String].Format(CultureInfo.InvariantCulture, "ConnectionManager_{0}", Me.UniqueId)
            ElseIf Me._connectionManagerThread.ThreadState = ThreadState.Running Then
                Throw New ThreadStateException("The request handling process is already running.")
            End If
           
            If Me._connectionManagerThread.ThreadState <> ThreadState.Unstarted Then
                Throw New ThreadStateException("The request handling process was not properly initialized so it could not be started.")
            End If
            Me._connectionManagerThread.Start()
           
            Dim waitTime As Long = DateTime.Now.Ticks + TimeSpan.TicksPerSecond * 50
            While Me.RunState <> State.Started
                Thread.Sleep(100)
                If DateTime.Now.Ticks > waitTime Then
                    Throw New TimeoutException("Unable to start the request handling process.")
                End If
            End While
        End Sub
       
        Public Overridable Sub [Stop]()
            ' Setting the runstate to something other than "started" and
            ' stopping the listener should abort the AddIncomingRequestToQueue
            ' method and allow the ConnectionManagerThreadStart sequence to
            ' end, which sets the RunState to Stopped.
            Interlocked.Exchange(Me._runState, CLng(State.Stopping))
            If Me._listener.IsListening Then
                Me._listener.[Stop]()
            End If
            Dim waitTime As Long = DateTime.Now.Ticks + TimeSpan.TicksPerSecond * 10
            While Me.RunState <> State.Stopped
                Thread.Sleep(100)
                If DateTime.Now.Ticks > waitTime Then
                    Throw New TimeoutException("Unable to stop the web server process.")
                End If
            End While
           
            Me._connectionManagerThread = Nothing
        End Sub
    End Class
   
    Public Class HttpRequestEventArgs
        Inherits EventArgs
Private _RequestContext As HttpListenerContext
        Public Property RequestContext() As HttpListenerContext
            Get
                Return _RequestContext
            End Get
            Private Set(ByVal value As HttpListenerContext)
                _RequestContext = value
            End Set
        End Property
       
        Public Sub New(ByVal requestContext As HttpListenerContext)
            Me.RequestContext = requestContext
        End Sub
    End Class
End Namespace


0
 

Author Comment

by:tom3030
ID: 24740650
Thanks for giving it a go - If you copy that code into visual studio it looks like there are around 11 or so errors (including the original problem, that you can't assign a default value (Nothing/Null) to an event handler). I think that the initial VB code was fairly close, but just needs the event handling to be tweaked to work as the C# code does.
0
 
LVL 83

Assisted Solution

by:CodeCruiser
CodeCruiser earned 1000 total points
ID: 24761667
I think you do not need to assign the null/nothing to the event. If you do not use the New keyword, its Nothing anyway.
0
 

Accepted Solution

by:
tom3030 earned 0 total points
ID: 24792986
Ok - I figured it out. As CodeCruiser said you can't set the default value of the event to Nothing. But the real issue was that the BeginInvoke simply becomes RaiseEvent in VB.Net i.e. RaiseEvent IncomingRequest(Me, e)

I'll copy the fully working code below.

Note: The way this currently works the page doesn't seem to expire in the browser, so it get's cached - to force it to re-load you'll have to do a refresh in the web browser.
MODULE (MAIN)
-------------
Imports System
Imports System.IO
Imports System.Net
Imports System.Text
 
Module Module1
 
    Sub Main(ByVal args As String())
        Using listener As WebServer = New WebServer(New Uri("http://localhost:8080/"))
            AddHandler listener.IncomingRequest, New EventHandler(Of HttpRequestEventArgs)(AddressOf WebServer_IncomingRequest)
            listener.Start()
            Console.WriteLine("Listener accepting requests: {0}", (listener.RunState = WebServer.State.Started))
            Console.WriteLine("Making requests...")
            Console.WriteLine("Press any key to close server.")
            Console.ReadLine()
            listener.Stop()
            listener.Dispose()
        End Using
    End Sub
 
    Public Sub WebServer_IncomingRequest(ByVal sender As Object, ByVal e As HttpRequestEventArgs)
        Dim response As HttpListenerResponse = e.RequestContext.Response
        Dim content As String = ("This is working: " & DateTime.Now.ToShortTimeString)
        Dim buffer As Byte() = Encoding.UTF8.GetBytes(content)
        response.StatusCode = 200
        response.StatusDescription = "OK"
        response.ContentLength64 = CLng(buffer.Length)
        response.ContentEncoding = Encoding.UTF8
        response.OutputStream.Write(buffer, 0, buffer.Length)
        response.OutputStream.Close()
        response.Close()
    End Sub
 
End Module
 
WEBSERVER CLASS
---------------
Imports System
Imports System.Globalization
Imports System.Net
Imports System.Threading
 
Class WebServer
    Implements IDisposable
    ' Events
    ' Fields
 
    Private _connectionManagerThread As Thread
    Private _disposed As Boolean
    Private _listener As HttpListener
    Private _runState As Long = Long.Parse(State.Stopped)
    Private _UniqueId As Guid
    Private _Url As Uri
 
    Public Enum State
        ' Fields
        Started = 3
        Starting = 2
        Stopped = 0
        Stopping = 1
    End Enum
 
    Public Event IncomingRequest As EventHandler(Of HttpRequestEventArgs)
 
    ' Methods
    Public Sub New(ByVal listenerPrefix As Uri)
        If Not HttpListener.IsSupported Then
            Throw New NotSupportedException("The HttpListener class is not supported on this operating system.")
        End If
        If (listenerPrefix Is Nothing) Then
            Throw New ArgumentNullException("listenerPrefix")
        End If
        Me._UniqueId = Guid.NewGuid
        Me._listener = New HttpListener
        Me._listener.Prefixes.Add(listenerPrefix.AbsoluteUri)
    End Sub
 
    Private Sub ConnectionManagerThreadStart()
        Interlocked.Exchange(_runState, Long.Parse(State.Starting))
        Try
            If Not Me._listener.IsListening Then
                Me._listener.Start()
            End If
            If Me._listener.IsListening Then
                Interlocked.Exchange(_runState, Long.Parse(State.Started))
            End If
            Try
                Do While (Me.RunState = State.Started)
                    Dim context As HttpListenerContext = Me._listener.GetContext
                    Me.RaiseIncomingRequest(context)
                Loop
            Catch exception1 As HttpListenerException
            End Try
        Finally
            Interlocked.Exchange(_runState, Long.Parse(State.Stopped))
        End Try
    End Sub
 
    Public Overridable Sub Dispose() Implements IDisposable.Dispose
        Me.Dispose(True)
        GC.SuppressFinalize(Me)
    End Sub
 
    Private Sub Dispose(ByVal disposing As Boolean)
        If Not Me._disposed Then
            If disposing Then
                If (Me.RunState <> State.Stopped) Then
                    Me.Stop()
                End If
                If (Not Me._connectionManagerThread Is Nothing) Then
                    Me._connectionManagerThread.Abort()
                    Me._connectionManagerThread = Nothing
                End If
            End If
            Me._disposed = True
        End If
    End Sub
 
    Protected Overrides Sub Finalize()
        Try
            Me.Dispose(False)
        Finally
            MyBase.Finalize()
        End Try
    End Sub
 
    Private Sub RaiseIncomingRequest(ByVal context As HttpListenerContext)
        Dim e As New HttpRequestEventArgs(context)
        Try
            RaiseEvent IncomingRequest(Me, e)
        Catch ex As Exception
        End Try
    End Sub
 
    Public Overridable Sub Start()
        If ((Me._connectionManagerThread Is Nothing) OrElse (Me._connectionManagerThread.ThreadState = ThreadState.Stopped)) Then
            Me._connectionManagerThread = New Thread(New ThreadStart(AddressOf Me.ConnectionManagerThreadStart))
            Me._connectionManagerThread.Name = String.Format(CultureInfo.InvariantCulture, "ConnectionManager_{0}", New Object() {Me.UniqueId})
        ElseIf (Me._connectionManagerThread.ThreadState = ThreadState.Running) Then
            Throw New ThreadStateException("The request handling process is already running.")
        End If
        If (Not Me._connectionManagerThread.ThreadState = ThreadState.Unstarted) Then
            Throw New ThreadStateException("The request handling process was not properly initialized so it could not be started.")
        End If
        Me._connectionManagerThread.Start()
        Dim waitTime As Long = (DateTime.Now.Ticks + TimeSpan.TicksPerSecond * 50)
        Do While (Me.RunState <> State.Started)
            Thread.Sleep(100)
            If (DateTime.Now.Ticks > waitTime) Then
                Throw New TimeoutException("Unable to start the request handling process.")
            End If
        Loop
    End Sub
 
    Public Overridable Sub [Stop]()
        Interlocked.Exchange(_runState, Long.Parse(State.Stopping))
        If Me._listener.IsListening Then
            Me._listener.Stop()
        End If
        Dim waitTime As Long = (DateTime.Now.Ticks + TimeSpan.TicksPerSecond * 10)
        Do While (Me.RunState <> State.Stopped)
            Thread.Sleep(100)
            If (DateTime.Now.Ticks > waitTime) Then
                Throw New TimeoutException("Unable to stop the web server process.")
            End If
        Loop
        Me._connectionManagerThread = Nothing
    End Sub
 
 
    ' Properties
    Public ReadOnly Property RunState() As State
        Get
            Return DirectCast(CInt(Interlocked.Read((Me._runState))), State)
        End Get
    End Property
 
    Overridable Property UniqueId() As Guid
        Get
            Return _UniqueId
        End Get
        Set(ByVal value As Guid)
            _UniqueId = value
        End Set
    End Property
 
    Overridable Property Url() As Uri
        Get
            Return _Url
        End Get
        Set(ByVal value As Uri)
            _Url = value
        End Set
    End Property
 
 
 
    ' Nested Types
 
End Class
 
 
Class HttpRequestEventArgs
    Inherits EventArgs
    ' Methods
    Public Sub New(ByVal requestContext As HttpListenerContext)
        Me.RequestContext = requestContext
    End Sub
 
    Private _RequestContext As HttpListenerContext
 
 
    ' Properties
    Property RequestContext() As HttpListenerContext
        Get
            Return _RequestContext
        End Get
        Set(ByVal value As HttpListenerContext)
            _RequestContext = value
        End Set
    End Property
 
End Class

Open in new window

0

Featured Post

How to Use the Help Bell

Need to boost the visibility of your question for solutions? Use the Experts Exchange Help Bell to confirm priority levels and contact subject-matter experts for question attention.  Check out this how-to article for more information.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A while ago, I was working on a Windows Forms application and I needed a special label control with reflection (glass) effect to show some titles in a stylish way. I've always enjoyed working with graphics, but it's never too clever to re-invent …
Since .Net 2.0, Visual Basic has made it easy to create a splash screen and set it via the "Splash Screen" drop down in the Project Properties.  A splash screen set in this manner is automatically created, displayed and closed by the framework itsel…
In response to a need for security and privacy, and to continue fostering an environment members can turn to for support, solutions, and education, Experts Exchange has created anonymous question capabilities. This new feature is available to our Pr…
Despite its rising prevalence in the business world, "the cloud" is still misunderstood. Some companies still believe common misconceptions about lack of security in cloud solutions and many misuses of cloud storage options still occur every day. …

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question