loading...

Easy and fast sockets in C# .Net Core

kerlantc profile image Pau Sabates ・2 min read

Alt Text
Working with sockets with C# can be really overwhelming due to its different libraries and many methods to choose from.
For example you have to deal with TcpClient, NetworkStream, TcpListener classes with really similar methods between them, but with different purposes, and within each class there are different ways to achieve the same goal.
So you end up searching in the internet and official documentation every time you need to work with sockets but you don’t know which of the many solutions you found is the more correct,fully asynchronous, production ready or more updated option.

The solution to your problems: SockNet

Socknet is a C# library, (.Net Standard 2.0) that works with the lastests versions of .Net Core, which can create a socket server or a client with just a few lines of code.
Let’s see how it works with a simple example that creates both a client and a server connected to each other:

Client:
This creates a socket client indicating the server address to connect asynchronously to it, and sends and receives data asynchronously once its connected:

  var client = new SocketClient("127.0.0.1", 80);

  if (await client.Connect())
  {
      await client.Send("Am I cool?");
      var recData = await client.ReceiveBytes();
  }

And…that’s all for the client!

Server:
The first step is to initialize the server to listen at a concrete port and also set the way the server will read from clients. In this case with the method ‘SetReaderBufferBytes(1024)’ it will read 1024 bytes with each connection, but more advanced types of reading can be set.

  var server = new SocketServer();
  server.InitializeSocketServer("127.0.0.1", 80);
  server.SetReaderBufferBytes(1024);
  server.StartListening();

The other types of reading such as reading with a start and end delimitator or to receive an exact number of bytes, can be found in the documentation:
Now that it’s initialized, let’s run the server!

  if(server.IsNewData())
  {
      var data = server.GetData();
      // Do whatever you want with data
      Task.Run(() => DoSomething(data, server));
  }

Here the socket will listen until new data arrives, and when it happens you can send it to be processed in a separate thread to keep listening to multiple users.
Now if you want to send data back to the client, just use this method:

server.ResponseToClient(data.key, "this is cool!");

And that’s all! A fully functional and robust socket client and server done, in just a few minutes and lines of code.

You can view the source code of this example here.

In order to download the library, just get its nuget package:
$ dotnet add package SockNet

Thanks for reading and I really hope this library can be helpful!!! :)

Posted on by:

Discussion

pic
Editor guide
 

Unfortunately it looks like this library doesn't support cancellation as far as I can see.

When I want to do socket programming in .net, I always find that the lower level Socket type is the best option, as it handles cancellation, can work with the new Memory<T> types, etc. so implementing a high performance client/server is made relatively easy.

Take, for example, the method signature for Socket.SendAsync. You can pass in a memory type, and it supports cancellation. Under the hood it will make use of a SocketAsyncEventArgs pool which will be familiar to anybody who’s used sockets in .net in an asynchronous manner even before the async/await support was available.

The TcpClient and UdpClient types only complicate things in my opinion.

 

That's true! It's planned as a feature that as an optional parameter the user can pass a timeout for instance or the token itself, and the library will have different overload methods to work under the hood with the cancellation token, for example with the Send or Receives methods. The idea is to satisfy the most common use cases and this is one for sure.
Thanks for your comment!

 

This looks like a great library. Usually when I need to work with sockets, I create the client in C# and server in C++ and this should be perfect for those kind of things!

 

What benefits does this have over using SignalR? I've found SignalR to be very nice to work with

 

Well maybe SignaIR has a different approach/goal. For example you'll use it for making real time websockets, and you are using its transport layer and protocol and building everything with its rules, and it works really good as you say! But if you just want to create a socket that works in the TCP layer sending and receiving bytes and nothing else, Socknet can be an option, if you want to avoid the more low level TCP libraries.
Hope this helps! Thank you!