WebSocket Sharp is an open-source library for implementing WebSocket in .NET applications.
As we saw in this tutorial, implementing a WebSocket connection manually is quite a pain. So it’s best to use a library that makes the job easier for us.
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 might expect from a WebSocket library, such as compression, authentication, header management, cookies. Among many, many other options.
Check the library’s documentation 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 establish a connection both as a server and as a client.
Server Example
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();
}
}
Client Example
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 repository at https://github.com/sta/websocket-sharp/
Unfortunately, WebSocketSharp also has its own problems. The main one is that it is only available for .NET Framework.
The community has responded by creating different forks. For example:
- Here is the library ported to .NET Core https://github.com/nozomi-ai/websocket-sharp/
- Here to .NET Standard https://github.com/PingmanTools/websocket-sharp/
However, in the next tutorial we will see how to use WatsonWebsockets, a more modern though less known library for making WebSocket connections in C#.

