Language: EN

csharp-websocketssharp

How to use WebSockets in C# with the WebSocket Sharp library

WebSocket Sharp is an open-source library for implementing WebSocket in .NET applications.

We already saw in this tutorial that implementing a WebSocket connection manually is quite a pain. So it’s best to use a library that makes our work easier.

WebSocketSharp is the most well-known and popular library for this job. It provides an easy-to-use, high-level API for implementing WebSocket in .NET applications.

WebSocketSharp implements all the functionalities we can expect in a WebSocket library, such as compression, authentication, header management, cookies, among many other options.

Check the documentation of the library for a list of available options and how to use them.

How to use WebSocketSharp

We can easily add the library to a .NET project through the corresponding Nuget package.

Install-Package WebSocketSharp

Here are some examples of how to use WebSocketSharp to make a connection as both a server and a client.

Example as a server

using WebSocketSharp.Server;
using WebSocketSharp;

public class TestService : WebSocketBehavior
{
    protected override void OnMessage(MessageEventArgs e)
    {
        Console.WriteLine("Received from client: " + e.Data);
        
        Send("Data from server");
    }

    protected override void OnError(WebSocketSharp.ErrorEventArgs e)
    {
        // do nothing
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        var ws = new WebSocketServer("ws://localhost:9006");

        ws.AddWebSocketService<TestService>("/Test");
        ws.Start();
        Console.ReadKey(true);
        ws.Stop();      
    }
}

Example as a client

using WebSocketSharp;

public class Program
{
    public static void Main(string[] args)
    {
        using var ws = new WebSocket("ws://localhost:9006/Test");
        ws.OnMessage += (sender, e) => Console.WriteLine("Received: " + e.Data);

        ws.Connect();
        ws.Send("Data from client");

        Console.ReadKey(true);
        ws.Close();
    }
}

WebSocketSharp is Open Source, and all the code and documentation is available in the project’s repository at https://github.com/sta/websocket-sharp/

Unfortunately, WebSocketSharp also has its own issues. The main one is that it is only available for .NET Framework.

The community has responded by creating different forks. For example:

However, in the next tutorial we will see the utility of WatsonWebsockets, a more modern but less known library for making WebSocket connections in C#.