WatsonWebsocket is an open-source library that provides an easy and fast implementation for WebSocket connections for C# applications. It is compatible with .NET Framework and .NET Core, and features a simple and easy-to-use API.
In previous tutorials, we have seen how to make a WebSocket connection without using any library, and here is a tutorial using WebsocketsSharp, the most popular WebSocket library for working with WebSockets in C#.
This time, we are going to see a third way, using the WatsonWebsocket library. Another option that, personally, is my favorite one today.
It is compatible with .NET 6 and later, and therefore cross-platform (Windows, Linux, Android, Mac, and iOS). It has never given me errors, the syntax is modern, and very easy to use.
Furthermore, WatsonWebsocket has a wide range of configuration options to adjust the library’s behavior, or at least all the ones I have ever needed to use.
How to Use WatsonWebsocket
We can easily add the library to a .NET project through the corresponding Nuget package.
Install-Package WatsonWebsocket
Here are some examples of how to use WatsonWebsocket extracted from the library’s documentation.
Example as a Server
using System.Text;
using WatsonWebsocket;
WatsonWsServer server = new WatsonWsServer("127.0.0.1", 9006, false);
server.ClientConnected += (s, args) => Console.WriteLine($"Client connected: {args.Client}");
server.ClientDisconnected += (s, args) => Console.WriteLine($"Client disconnected: {args.Client}");
server.MessageReceived += (s, args) => Console.WriteLine($"Message received from {args.Client} : {Encoding.UTF8.GetString(args.Data)}");
server.Start();
Console.ReadLine();
Example as a Client
using System.Text;
using WatsonWebsocket;
WatsonWsClient client = new WatsonWsClient("127.0.0.1", 9006, false);
client.ServerConnected += (s, args) => Console.WriteLine("Server connected");
client.ServerDisconnected += (s, arg) => Console.WriteLine("Server disconnected");
client.MessageReceived += (s, args) => Console.WriteLine($"Message from server: {Encoding.UTF8.GetString(args.Data)}");
client.Start();
await client.SendAsync("hello");
Console.ReadLine();
As we can see, using WatsonWebsocket is, by far, the simplest of the options we have seen so far. For me, it is an example of a well-made library.
It is much simpler and more modern than the old WebsocketsSharp, and infinitely simpler than using them “manually”.
WatsonWebsocket is Open Source, and all the code and documentation is available in the project repository on GitHub - jchristn/WatsonWebsocket

