Skip to content

luca-schlecker/SwebSocket

Repository files navigation

SwebSocket

NuGet Downloads GitHub License NuGet Version

A handwritten, easy to use WebSocket Library that aims to:

Disclaimer

Warning

This is a fun-project and may contain severe errors. You should probably not use this in production.

Installation

This Library is on NuGet and can thus be installed in many ways, including but not limited to:

There are more provided on the NuGet Page.

Examples

Client

Echo Client (Manual)

using SwebSocket;

var ws = WebSocket
    .Connect()
    .To("wss://echo.websocket.org/")
    .Build();

// Discard first message
_ = ws.Receive();

while (true) {
    var line = Console.ReadLine();
    if (line == null) break;
    ws.Send(line);
    var answer = ws.Receive();
    if (answer is TextMessage text)
        Console.WriteLine($"Received: {text.Text}");
}

Echo Client (Background Poller)

using SwebSocket;

var ws = WebSocket
    .Connect()
    .To("wss://echo.websocket.org/")
    .Build();

ws.OnMessage += (_, message) => {
    if (message is TextMessage text)
        Console.WriteLine($"Received: {text.Text}");
};

BackgroundMessagePoller.Poll(ws);

while (true) {
    var line = Console.ReadLine();
    if (line == null) break;
    ws.Send(line);
}

Important

The WebSocket.OnMessage event will (by default) not be raised. You can raise it manually by calling WebSocket.EmitMessage(Message) or use a Poller which will call it under the hood.

Server

Echo Server (Manual)

using SwebSocket;

var listener = new Listener(IPAddress.Any, 3000);

while (true) {
    var ws = listener.Accept();

    try {
        while (true) {
            var message = ws.Receive();
            ws.Send(message);
        }
    }
    catch { }
}

Echo Server (Blocking Poller)

using SwebSocket;

var listener = new Listener(IPAddress.Any, 3000);

while (true) {
    var ws = listener.Accept();

    ws.OnMessage += (_, m) => ws.Send(m);
    new BlockingMessagePoller(ws).Poll();
}

Secure Connection

Client

using SwebSocket;

var listener = new Listener(IPAddress.Any, 3000)
    .UseSsl(SslOptions.NoSsl)                // No Ssl
    .UseSsl(SslOptions.ForServer(identity)); // X509Certificate2 as Identity

// ...

Server

using SwebSocket;

var ws = WebSocket
    .Connect()
    .To("wss://127.0.0.1/")
    .UseSsl(SslOptions.ForClient(
        "custom authority", // The name to validate the certificate against
        caCertificates      // X509Certificate2Collection
    ))
    .Build();

// ...

Related Projects