I'm at a bit of a loss as to how to properly implement the asynchronous methods for TcpListner and TcpClient int .NET. I've read over quite a few posts on hear and I believe I have the code to accept new clients on the server taken care of. Here is the code for acception new connections:
Public Sub Start()
m_oListener = New TcpListener(m_oIpAddress, m_iPort)
m_oListener.Start()
m_oListener.BeginAcceptTcpClient(New AsyncCallback(AddressOf OnAcceptClient), m_oListener)
End Sub
Public Sub OnAcceptClient(ByVal ar As IAsyncResult)
Dim listener As TcpListener = CType(ar.AsyncState, TcpListener)
Dim client As TcpClient = listener.EndAcceptTcpClient(ar)
If listener.Server.IsBound Then
ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf OnHandleClient), client)
listener.BeginAcceptTcpClient(New AsyncCallback(AddressOf OnAcceptClient), listener)
End If
End Sub
What I'm not sure about is what to do with the client once the connection is established. From what I've seen, usually people create a new thread for each client connected to prevent IO reads from blocking the application.
My application will have up to 100 clients connected at any given time. If I spin off a new thread for each client then I'll have 100 or so threads. Is that correct? I think I'm just missing something with the async methods in the .NET framework.
Most of the example I see have the server accept the connection, read in a short message (e.g. "hello server") and then close the client and shutdown the server. This doesn't help me understand the proper way to maintain a large number of active clients over a large period of time.
Thanks for any help in advance.