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.
- 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.
-
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.
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();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")].
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));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.