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:
' FORM CLASS Private Sub DoListen() Try mobjListener = New TcpListener(5000) mobjListener.Start() Do Dim x As New Client(mobjListener.AcceptTcpClient) AddHandler x.Connected, AddressOf OnConnected AddHandler x.Disconnected, AddressOf OnDisconnected AddHandler x.LineReceived, AddressOf OnLineReceived mcolClients.Add(x.ID, x) Dim params() As Object = {"New connection"} Me.Invoke(New StatusInvoker(AddressOf Me.UpdateStatus), params) Loop Until False Catch End Try 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:
'CLIENT CLASS Public Sub New(ByVal client As TcpClient) moClient = client RaiseEvent Connected(Me) moClient.GetStream.BeginRead(marData, 0, 1024, AddressOf DoStreamRecieve, Nothing) 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


Reply With Quote