NetSocket 1.1.1
dotnet add package NetSocket --version 1.1.1
NuGet\Install-Package NetSocket -Version 1.1.1
<PackageReference Include="NetSocket" Version="1.1.1" />
<PackageVersion Include="NetSocket" Version="1.1.1" />
<PackageReference Include="NetSocket" />
paket add NetSocket --version 1.1.1
#r "nuget: NetSocket, 1.1.1"
#:package NetSocket@1.1.1
#addin nuget:?package=NetSocket&version=1.1.1
#tool nuget:?package=NetSocket&version=1.1.1
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
IMessageHandlerimplementations, optionally mapped via[Module("name")]. WebSocketMiddlewarefor accepting WS upgrades and optional token validation.- Convenience extensions to send JSON messages to single connections, users, segments, or broadcast.
- Flexible
IMessageHandlerregistration, supporting direct DI or using the defaultModuleHandler.
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 toIMessageHandler.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
IMessageHandlerimplementations and end-to-end tests. - Provide authentication/authorization examples.
- Add configuration options for buffer sizes, timeouts, and message limits.
| Product | Versions 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. |
-
net8.0
- Microsoft.AspNetCore.Http.Abstractions (>= 2.3.0)
- Microsoft.Extensions.Logging.Abstractions (>= 8.0.3)
NuGet packages
This package is not used by any NuGet packages.
GitHub repositories
This package is not used by any popular GitHub repositories.