In the third post about XGain I would like to say something about the heart of server. TcpListener is a great class to build server. It has a normal and async methods, you can choose between Socket and TcpClient. Unfortunately writing this same logic for new project might be boring. The most common steps:
- choose entry port
- create new instance of TcpListener
- start listening
- create a main loop for processing
- handle new request
After these five steps you can say – “I have my own TCP/IP server!”. However, reality is more complicated. After some time you will have to think about more advanced features. Network layer is really prone to errors. Problems with connection, lags, timeouts or even issues related to serialization. Testability of the code could be another challenge. Sometimes it is really hard to divide layer of networking from business logic, especially when you are dealing with huge amount of data.
XGain is a small solution which allows you to create TCP/IP server in few minutes. Let’s start from the IServer – an interface which allows you create server and easy mock networking layer. Currently this interface has two methods and three events.
- OnStart raises after server initialization – it is a good entry point to log information about listening server.
- OnError provides you a way to reach and process any error from server
- The most important event is OnNewMessage. This is a handler for any new request to your server.
Each of these events has a simple model based on the EventArgs.
API for listening contains two methods and is really simple. Both of them have a CancellationToken structure which allows you to stop server after any Cancel request or defined timeout.
StartSynchronously as the name suggests starts a synchronously listener based on the Socket level.
The second listener, StartParallel contains parallel excecution. This methods contains extra parameter – maxDegreeOfParallelism. This param is optional and by default, task scheaduler will decide how many request may be processed in the same time.
Under the public methods you can find four private. The first of them – ProcessSocketConnection is being used by both listeners. This method receives a ISocket wrapper around internal .NET Socket class. I’ve described this interface in the previous post. Next three methods are really simple and they handles the event invocation.
XGain in version 1.0.0 is available on the nuget.org. You can install my server by typing this line in nuget command prompt.
In the next post I’m going to show a demo of XGain. Feel free to ask, comment and give feedback!