Skip to content

FrancoDurand/NetSocket

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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.

About

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages