zondag 4 december 2016

TCP Server in C#

How to write a TCP Server in C#

What is the most performant way to implement a TCP server in C#? While trying to find an example of a http server in C# I came across this example:

Although is looks pretty good, it lacks a few details:

It can't be stopped in a decent way
It can't be run as a windows service
It doesn't show which exceptions to catch

This is part one of a serie about implementing a decent tcp server through sockets.

Part two can be found here.

Parts of a TCP Server

A TCP server based on sockets in C# is actually pretty simple. It consists of two parts:

A listener, this is a socket that listens for client connections
A handler, this is a socket that handles the communication with the client from the moment the connection is made.

For both parts the Socket class is used. The socket class examples however show the synchronous way of sending and receiving data. While that is fine for an example, it's not the preferred way of writing a scalable, high performant TCP Server. In that case, the asynchronous methods beginXXX must be used. So how does asynchronous communication with sockets work?

How does it work?

Start the listener

First let's start a socket that listens for new connections.

In the BeginAccept method a callback method has to be set. This callback method will be called whenever a new client starts a new connection with the ser.

A client connects to the server

When a client connects to the server, the callback will be triggered.

In the callback a new socket will be made which handles all communication with the client, so the Listener socket will be free for accepting new connections.

Server starts receiving data

The clientsocket calls BeginReceive to asynchronously receive the data.

Restart listening for new connections

On the listenersocket BeginAccept has to be called again, to restart listening for new connections.

This allows new clients to connect. For each new connection, a ClientSocket will be created.

This concludes the overview. In part two the TCP Server will be implemented.

Geen opmerkingen:

Een reactie posten