Help with event driven TCP server

Ben picture Ben · Mar 16, 2011 · Viewed 9.9k times · Source

I'm working on an "application system" , where I also need to make a server application. I'm working in C# (.NET 4.0). The server will mainly collect data from different POS applications / clients (which should be around 50-100, but the server should be capable of handling also around 200-300 clients). From a single client a server will probably receive around 1KB about 100x times a day. The server mainly needs to accept the data, decrypt it and store it to disk. It should also check for changes in specific directory in order to send new configurations to clients, which shouldn't be very often.

I'm quite new to C# and server programming so please bear with me. I thought about using threadpooling and async methods (there is a nice example using that in a book "C# in a nutshell"). But I spend quite some time looking for best solution and I found this. But multithreading brings more problems than benefits in my case. Thus I thought about even driven server. "A single process, handle every event (accepted connection, data available to read, can write to client, ...) on a callback." from " what is event driven web server". I find that the best solution to my problem.

But I have no idea on how to code it, I couldn't find any examples about event driven servers. As far as I understand it I should make one thread (+ 1 for GUI), then create a TCP listener and then somehow create events so that when TCP listener could accept a client the event would fire and wake up the server, also when data to read from clients would be available it would wake up the server.

Please help me out to code this, I'm totally lost. I know how I could do this using

while(true)
{
   check if client wants to connect
        accept client and add it to client list
   iterate through client list and check if anyone is sending data ...
        accept data and store it
   ...
  }

But that is not event driven and is wasting CPU. Server will not be very active, so I'd like to make it as efficient as possible.

Some examples would really help.

Thank you for your time and answers.

p.s. Can I use just one port for all the clients?

EDIT: To clarify, I want to code an event driven server, but I don't know how to, thus I just made an example of what I know (client polling).

Answer

Stephen Cleary picture Stephen Cleary · Mar 16, 2011

First, if you're new to C# and multithreading and sockets, that is a lot to bite off for your first project. I recommend learning these individually.

That said, you may find Nito.Async.Sockets helpful; it includes an event-driven server socket and handles the multithreading concerns for you.