NetSocket 1.1.1

dotnet add package NetSocket --version 1.1.1
                    
NuGet\Install-Package NetSocket -Version 1.1.1
                    
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="NetSocket" Version="1.1.1" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="NetSocket" Version="1.1.1" />
                    
Directory.Packages.props
<PackageReference Include="NetSocket" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add NetSocket --version 1.1.1
                    
#r "nuget: NetSocket, 1.1.1"
                    
#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.
#:package NetSocket@1.1.1
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=NetSocket&version=1.1.1
                    
Install as a Cake Addin
#tool nuget:?package=NetSocket&version=1.1.1
                    
Install as a Cake Tool

NetSocket

NetSocket is a lightweight, framework-agnostic .NET library providing basic WebSocket infrastructure for ASP.NET Core applications. It includes connection management, modular message dispatching, helper extensions for sending messages, and middleware to accept and process WebSocket connections.

NetSocket focuses strictly on WebSocket primitives and routing logic—it does not depend on application-specific services or persistence. It's designed to integrate into larger ASP.NET Core projects requiring real-time communication.

Key Features

  • Connection management with optional grouping/segments (rooms).
  • Envelope-based messaging (module/action/payload) for modular routing.
  • Message dispatching to IMessageHandler implementations, optionally mapped via [Module("name")].
  • WebSocketMiddleware for accepting WS upgrades and optional token validation.
  • Convenience extensions to send JSON messages to single connections, users, segments, or broadcast.
  • Flexible IMessageHandler registration, supporting direct DI or using the default ModuleHandler.

Project Structure

  • Core/

    • ConnectionManager.cs — tracks active connections and segment membership.
    • WebSocketConnection.cs — represents an individual connection with optional user association.
    • Envelope.cs — standard message format: { module, action, payload }.
    • MessageDispatcher.cs — deserializes envelopes and routes them to IMessageHandler.
    • IMessageHandler.cs — handler contract.
    • ModuleAttribute.cs — maps handlers to module names.
  • Middleware/

    • WebSocketMiddleware.cs — accepts WebSocket upgrades, validates tokens, and forwards messages to the dispatcher.
  • Extensions/

    • WebSocketExtensions.cs — helper methods to send JSON messages to connections, users, segments, or broadcast.

Minimal Integration Example (ASP.NET Core)

var builder = WebApplication.CreateBuilder(args);

// Register NetSocket core services
builder.Services.AddSingleton<ConnectionManager>();
builder.Services.AddSingleton<MessageDispatcher>();
// Register a ModuleHandler
builder.Services.AddScoped<IMessageHandler, ModuleHandler>();

//Or using Structor
builder.Services.AddSingleton<MessageDispatcher>(sp =>
{
    var manager = sp.GetRequiredService<ConnectionManager>();
    var handlers = sp.GetServices<IMessageHandler>(); // register your handlers
    var logger = sp.GetRequiredService<ILogger<MessageDispatcher>>();
    return new MessageDispatcher(manager, handlers, logger);
});

var app = builder.Build();

// Optional token validation function
Func<string, Task<string?>> validateToken = async token =>
{
    await Task.CompletedTask;
    return token == "demo" ? "user-123" : null;
};

// Enable WebSockets
app.UseWebSockets();

// Add WebSocket middleware
app.UseMiddleware<WebSocketMiddleware>(
    app.Services.GetRequiredService<ConnectionManager>(),
    app.Services.GetRequiredService<MessageDispatcher>(),
    validateToken, // optional
    "/ws" // optional route, default "/"
);

app.Run();

Message Format (Envelope)

All messages should be JSON envelopes:

{
  "module": "notifications",
  "action": "create",
  "payload": { "text": "hello" }
}

Routing is performed using the module value. Implement IMessageHandler for each module and optionally annotate with [Module("name")].

Client Example (Browser JavaScript)

const ws = new WebSocket('ws://localhost:5000/ws?token=demo');

ws.onopen = () => console.log('connected');
ws.onmessage = ev => console.log('received', ev.data);

const envelope = { module: 'notifications', action: 'create', payload: { text: 'hello' } };
ws.send(JSON.stringify(envelope));

Contributing

Contributions are welcome. Suggested improvements:

  • Add sample IMessageHandler implementations and end-to-end tests.
  • Provide authentication/authorization examples.
  • Add configuration options for buffer sizes, timeouts, and message limits.
Product Compatible and additional computed target framework versions.
.NET net8.0 is compatible.  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.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed.  net10.0 was computed.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.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.1 208 11/9/2025
1.1.0 172 11/9/2025
1.0.1 163 11/7/2025
1.0.0 162 11/6/2025