How to implement a TCP server that can handle thousands of connections?


The class TcpServer of the TCP/IP CF implements a server that listens on a TCP port. Internally TcpServer uses a dedicated thread that executes a process where a TcpListener accepts new connections.


Initialization of TcpServer:

The constructor of TcpServer accepts tree parameters; a name, an IP address and a port where a TcpListener will be listening for new connections. The parameter name allows identifying the TcpServer in applications that use more than one TcpServer.


Starting and stopping TcpServer:

The method Start() starts the process of listening in a dedicated thread and the method Stop() stops the process. A timeout parameter can be passed when stopping the TcpServer.


Handling new connections:

TcpServer raises the event ClientConnected(). A reference to the Socket object used to receive/send data from/to the connected client is included in the event arguments. The event handler for ClientConnected() must return fast to allow TcpServer to continue accepting connections. A way to return fast from the event handler is scheduling the process that communicates with the socket in a separate thread.


Example of using TcpServer:

In the project called Server in the solution TemperatureClientServer a TcpServer is used to receive temperature updates from concurrent clients.

Last edited Aug 4, 2013 at 3:55 PM by valcarcel, version 2