Language: EN

csharp-watson-websocket

How to use WebSockets in C# with the WatsonWebSocket library

WatsonWebsocket is an open-source library that provides an easy and fast implementation for WebSocket connections for C# applications. It is compatible with the .NET Framework and .NET Core, and has 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 will see a third way, using the WatsonWebSocket library. Another option that, personally, is the one I like the most today.

It is compatible with .NET 6 and above, 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.

In addition, WatsonWebsocket has a large number of configuration options to adjust the behavior of the library, 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 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 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 modern than the old WebsocketsSharp, and infinitely simpler than using them “by hand.”

WatsonWebsocket is Open Source, and all the code and documentation is available in the project’s repository on GitHub - jchristn/WatsonWebsocket