Sai.MessageHub 1.0.3

There is a newer version of this package available.
See the version list below for details.
dotnet add package Sai.MessageHub --version 1.0.3
NuGet\Install-Package Sai.MessageHub -Version 1.0.3
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Sai.MessageHub" Version="1.0.3" />
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add Sai.MessageHub --version 1.0.3
#r "nuget: Sai.MessageHub, 1.0.3"
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install Sai.MessageHub as a Cake Addin
#addin nuget:?package=Sai.MessageHub&version=1.0.3

// Install Sai.MessageHub as a Cake Tool
#tool nuget:?package=Sai.MessageHub&version=1.0.3

Sai.MessageHub

Simple WebSocket message handler implemented as aspnetcore middleware. All messages are sent as text, serialised as JSON in the following format: { "Type": "type", "Data": any } Clients can send messages to the server and can add handlers for message types it wants to receive. Server can do the same, plus has the ability to respond to the client that sent the message, or send a message to all clients.

Example Usage

Program.cs

using Sai.MessageHub;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddMessageHub();
builder.Services.AddHostedService<MyWorker>(); // Example worker which sends the time to all MessageHub clients every second

var app = builder.Build();

app.UseMessageHub();

// Message handler for "counter" type. Generic type <T> relates to data type.
// Can map multiple handlers to the same type if required.
app.MapMessageHandler<int>("counter", (context, data) =>
{
    context.SendMessageToClient("counter-response", data); // echo back to sender
    context.SendMessageToAllClients("last-counter-update", DateTime.UtcNow); // send last update to all clients
});

app.Run();

MyWorker.cs

public class MyWorker : BackgroundService
{
    private readonly ILogger<MyWorker> _logger;
    private readonly IMessageHubService _messageHubService;
    public MyWorker(ILogger<MyWorker> logger, IMessageHubService messageHubService)
    {
        _logger = logger;
        _messageHubService = messageHubService;
    }

    protected override Task ExecuteAsync(CancellationToken stoppingToken)
    {
        return Task.Run(() =>
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                stoppingToken.WaitHandle.WaitOne(1000);
                _messageHubService.SendMessageToAllClients("time", DateTime.UtcNow);
            }
        });
    }
}

client.js

document.addEventListener("DOMContentLoaded", async () => {
    const messageHub = new MessageHub();

    messageHub.addMessageHandler("time", data => {
        document.querySelector(".time").innerText = data;
    });

    messageHub.addMessageHandler("counter-response", data => {
        document.querySelector(".counter-response").innerText = data;
    });

    messageHub.addMessageHandler("last-counter-update", data => {
        document.querySelector(".last-counter-update").innerText = data;
    });

    try
    {
        await messageHub.connect();
            
        let counter = 0;
        setInterval(() => {
            counter++;
            messageHub.sendMessage("counter", counter);
        }, 1000);
    }
    catch(err)
    {
        alert(err);
    }

});

messageHub.js

class MessageHub {

    constructor() {
        this.websocket = null;
        this.handlers = [];
    }

    connect() {
        return this.connectUri("ws://" + window.location.host + "/");
    }

    connectUri(wsUri) {
        return new Promise((resolve, reject) => {
            this.websocket = new WebSocket(wsUri);

            this.websocket.onopen = evt => {
                resolve();
            };

            this.websocket.onclose = evt => {
                this.websocket.close();
            };

            this.websocket.onmessage = evt => {
                const message = JSON.parse(evt.data);
                this.handlers.forEach(handler => {
                    if (handler.type == message.Type) {
                        handler.delegate(message.Data);
                    }
                });
            };

            this.websocket.onerror = evt => {
                console.error(evt);
            };
        });
    }

    sendMessage(type, data) {
        this.websocket.send('{"Type":"' + type + '","Data":' + JSON.stringify(data) + '}');
    }

    addMessageHandler(type, delegate) {
        this.handlers.push({ type: type, delegate: delegate });
    }
}
Product Compatible and additional computed target framework versions.
.NET net6.0 is compatible.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 was computed.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last updated
1.1.2 405 8/25/2022
1.1.1 435 4/1/2022
1.1.0 236 1/7/2022
1.0.3 280 12/17/2021
1.0.2 264 12/17/2021
1.0.1 300 12/17/2021
1.0.0 300 12/17/2021