Reputation: 395
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.
Upvotes: 3
Views: 3218
Reputation: 48959
Once you have extracted the reference to a TcpClient
in your OnAcceptClient
callback you will want to get the NetworkStream
via GetStream
and then call BeginRead
(or BeginWrite
) immediately to start the asynchronous operation. You will chain the next BeginRead
after you have called EndRead
from the callback just like you are doing with the TcpListener
.
Upvotes: 2
Reputation:
You could have 100 threads all handling one client each and that would be fine. You can also have one thread that loops through all of your clients and asynchronously handles I/O.
By making this asynchronous you don't have to worry about your single threading taking too long to process each connection.
If you are going to scale much higher than what you are talking about, handling multiple clients per thread will be necessary.
Pseudo code:
foreach TcpClient
if DataAvailable
BeginRead()
Upvotes: 1