Hi,

I been following an MSDN article on how to make a Multi-User chat server. Although Im not making a chat server, im interested in the Multi-User part of socket programming.

But the MSDN article doesn't seem to make sense, and my code version doesn't work.

The article is here: Creating a Multi-User TCP Chat Application

Im only interested in the Chat Server which is halfway down the page. The article uses this code to wait for incoming connections and add the clients to a hashtable

VB Code:
  1. ' FORM CLASS
  2.   Private Sub DoListen()
  3.     Try
  4.       mobjListener = New TcpListener(5000)
  5.  
  6.       mobjListener.Start()
  7.       Do
  8.         Dim x As New Client(mobjListener.AcceptTcpClient)
  9.  
  10.         AddHandler x.Connected, AddressOf OnConnected
  11.         AddHandler x.Disconnected, AddressOf OnDisconnected
  12.         AddHandler x.LineReceived, AddressOf OnLineReceived
  13.         mcolClients.Add(x.ID, x)
  14.  
  15.         Dim params() As Object = {"New connection"}
  16.         Me.Invoke(New StatusInvoker(AddressOf Me.UpdateStatus), params)
  17.       Loop Until False
  18.     Catch
  19.     End Try
  20.   End Sub

The problem is the Line

Dim x As New Client(mobjListener.AcceptTcpClient)

Client is a custom Class that represents a client socket. The classes New method is called when that line is executed.

VB Code:
  1. 'CLIENT CLASS
  2.     Public Sub New(ByVal client As TcpClient)
  3.         moClient = client
  4.         RaiseEvent Connected(Me)
  5.         moClient.GetStream.BeginRead(marData, 0, 1024, AddressOf DoStreamRecieve, Nothing)
  6.     End Sub

When a new instance of Client is created it raises a Connected Event, but that event is raised before the main form has chance to create a handler for the event. So it run like this

Dim x As New Client(mobjListener.AcceptTcpClient)
Creates a new instance of Client

RaiseEvent Conected(Me)
Clients new raises a Connected Event

AddHandler x.Connected, AddressOf OnConnected
The form creates a handler to capture the OnConnected event AFTER the new method raised it. So now the handler doesn't run


I can work round this because I know when the above code is run, then there must of been a new connection.

Im just wondering why MSDN doesn it like the above when it doesn't work that way

Thanks