StormSocket 3.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package StormSocket --version 3.0.0
                    
NuGet\Install-Package StormSocket -Version 3.0.0
                    
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="StormSocket" Version="3.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="StormSocket" Version="3.0.0" />
                    
Directory.Packages.props
<PackageReference Include="StormSocket" />
                    
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 StormSocket --version 3.0.0
                    
#r "nuget: StormSocket, 3.0.0"
                    
#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 StormSocket@3.0.0
                    
#: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=StormSocket&version=3.0.0
                    
Install as a Cake Addin
#tool nuget:?package=StormSocket&version=3.0.0
                    
Install as a Cake Tool

<p align="center"> <img src="assets/stormsocket.png" alt="StormSocket" width="256" /> </p>

<h1 align="center">StormSocket</h1>

<p align="center"> <a href="LICENSE"><img src="https://img.shields.io/badge/License-MIT-green.svg" alt="License" /></a> <a href="https://www.nuget.org/packages/StormSocket"><img src="https://img.shields.io/nuget/v/StormSocket.svg" alt="NuGet" /></a> <img src="https://img.shields.io/badge/.NET-6.0%20|%207.0%20|%208.0%20|%209.0%20|%2010.0-blue" alt=".NET" /> </p>

<p align="center">Modern, high-performance, event-based TCP/WebSocket/SSL library for .NET built on <b>System.IO.Pipelines</b>.</p>

<p align="center"> <a href="https://suleymanbyzt.github.io/StormSocket/docs/getting-started.html"><b>Getting Started</b></a> · <a href="https://suleymanbyzt.github.io/StormSocket/docs/features.html">Features</a> · <a href="https://suleymanbyzt.github.io/StormSocket/docs/configuration.html">Configuration</a> · <a href="https://suleymanbyzt.github.io/StormSocket/docs/examples.html">Examples</a> </p>

Zero subclassing required. Subscribe to events, configure options, and go. Server and client included.

Why StormSocket?

  • Pooled I/OSystem.IO.Pipelines buffer pool + ArrayPool for send encoding, minimal GC pressure
  • Backpressure that actually works — configurable pipe thresholds, OS TCP window propagates upstream
  • Subscribe, don't subclassserver.OnDataReceived += handler, no inheritance chains
  • SSL is a config flag — same server, add SslOptions, done
  • Middleware pipeline — rate limiting, auth, logging as composable plugins
  • Built-in pub/sub — named groups for chat rooms, game lobbies, ticker feeds

Features

  • Event-based API - no subclassing, just server.OnDataReceived += handler
  • TCP Server & Client with optional message framing (raw, length-prefix, delimiter)
  • WebSocket Server & Client with full RFC 6455 compliance (text, binary, ping/pong, close, fragmentation/continuation frames, client-side masking)
  • SSL/TLS as a simple configuration option on any server or client
  • Auto-reconnect - clients automatically reconnect on disconnect with configurable delay and max attempts
  • System.IO.Pipelines for zero-copy I/O with built-in backpressure
  • Automatic heartbeat with configurable ping interval and dead connection detection (missed pong counting)
  • Session management - track, query, broadcast, and kick connections
  • Groups/Rooms - named groups for targeted broadcast (chat rooms, game lobbies, etc.)
  • WebSocket authentication - access path, query params, headers (cookies, tokens) before accepting connections via OnConnecting event
  • Rate limiting middleware - opt-in per-session or per-IP rate limiting with configurable window, action (disconnect/drop), and exceeded event
  • Middleware pipeline - intercept connect, disconnect, data received, data sending, and errors (works on both server and client)
  • Backpressure & buffer limits - configurable send/receive pipe limits prevent memory exhaustion
  • Per-session user data - session.Items dictionary + strongly-typed session.Get<T> / session.Set<T> via SessionKey<T> — no external dictionary needed
  • Slow consumer detection - SlowConsumerPolicy per session: Wait (block), Drop (skip), or Disconnect (close)
  • Message fragmentation - automatic reassembly of fragmented WebSocket messages (RFC 6455 Section 5.4) with MaxMessageSize limit and send-side fragmentation helpers
  • Connection idle timeout - automatically close connections that haven't sent any application-level data within a configurable period (ping/pong does NOT reset the timer)
  • Disconnect reason tracking - OnDisconnected provides a DisconnectReason enum (ClosedByClient, ClosedByServer, Aborted, ProtocolError, TransportError, HeartbeatTimeout, HandshakeTimeout, SlowConsumer, GoingAway, RateLimited, IdleTimeout)
  • Handshake timeout - configurable timeout for WebSocket upgrade (DoS protection)
  • TCP Keep-Alive - fine-tuning options (idle time, probe interval, probe count)
  • Multi-target: net6.0, net7.0, net8.0, net9.0, net10.0
  • Structured logging via ILoggerFactory — zero overhead when disabled, structured output when enabled
  • Zero dependencies beyond System.IO.Pipelines and Microsoft.Extensions.Logging.Abstractions

Quick Start

dotnet add package StormSocket

TCP Server

var server = new StormTcpServer(new ServerOptions
{
    EndPoint = new IPEndPoint(IPAddress.Any, 5000),
});

server.OnDataReceived += async (session, data) =>
{
    await session.SendAsync(data); // echo
};

await server.StartAsync();

WebSocket Server

var ws = new StormWebSocketServer(new ServerOptions
{
    EndPoint = new IPEndPoint(IPAddress.Any, 8080),
    WebSocket = new WebSocketOptions
    {
        Heartbeat = new() { PingInterval = TimeSpan.FromSeconds(15), MaxMissedPongs = 3 },
        Compression = new() { Enabled = true },
    },
});

ws.OnConnected += async session =>
{
    session.Set(UserId, "abc");       // type-safe session data
    ws.Groups.Add("lobby", session);  // join a room
};

ws.OnMessageReceived += async (session, msg) =>
{
    await ws.BroadcastTextAsync(msg.Text, excludeId: session.Id);
};

await ws.StartAsync();

WebSocket Client

var client = new StormWebSocketClient(new WsClientOptions
{
    Uri = new Uri("ws://localhost:8080"),
    Reconnect = new() { Enabled = true, Delay = TimeSpan.FromSeconds(2) },
    Subprotocols = ["graphql-ws"],
});

client.OnMessageReceived += async msg => Console.WriteLine(msg.Text);
await client.ConnectAsync();
await client.SendTextAsync("Hello!");

SSL — one line

var server = new StormWebSocketServer(new ServerOptions
{
    EndPoint = new IPEndPoint(IPAddress.Any, 443),
    Ssl = new() { Certificate = X509CertificateLoader.LoadPkcs12FromFile("cert.pfx", "pass") },
});

Authentication

ws.OnConnecting += async context =>
{
    string? token = context.Headers.GetValueOrDefault("Authorization");
    if (!IsValid(token))
        context.Reject(401, "Invalid token");
    else
        context.Accept();
};

Session Data — string keys or type-safe

// String keys
session.Items["role"] = "admin";

// Strongly-typed (no casts, compile-time safe)
static readonly SessionKey<string> UserId = new("userId");
session.Set(UserId, "abc123");
string id = session.Get(UserId);

Groups, Broadcast, Rate Limiting

ws.Groups.Add("room:vip", session);
await ws.Groups.BroadcastAsync("room:vip", data, excludeId: session.Id);

server.UseMiddleware(new RateLimitMiddleware(new RateLimitOptions
{
    Window = TimeSpan.FromSeconds(10), MaxMessages = 100,
}));

Slow Consumer Policy

var server = new StormWebSocketServer(new ServerOptions
{
    SlowConsumerPolicy = SlowConsumerPolicy.Drop, // Wait | Drop | Disconnect
    MaxConnections = 50_000,
});

Idle Timeout

var server = new StormWebSocketServer(new ServerOptions
{
    WebSocket = new WebSocketOptions
    {
        IdleTimeout = TimeSpan.FromMinutes(5), // close if no data for 5 min
    },
});
// ping/pong does NOT reset the timer — only real messages count

Disconnect Reasons

ws.OnDisconnected += async (session, reason) =>
{
    // ClosedByClient | ClosedByServer | HeartbeatTimeout | SlowConsumer
    // ProtocolError | TransportError | RateLimited | GoingAway | IdleTimeout | ...
    Console.WriteLine($"#{session.Id}: {reason}");
};

Full details: Features Guide | Examples | Configuration

Architecture

Principle How
Composition over inheritance Flat structure, no deep inheritance chains.
System.IO.Pipelines Zero-copy I/O with kernel-level backpressure.
Event-based API Subscribe to events, no need to subclass.
SSL as decorator Same server, just add SslOptions.
Integer session IDs Interlocked.Increment (fast, sortable) instead of Guid.
Write serialization Per-session SemaphoreSlim lock prevents frame corruption.
Interface hierarchy INetworkSession (base) → ISession (connection-oriented) → WebSocketSession (WS-specific). Ready for future UDP.

Benchmarks

Echo round-trip: 100 concurrent clients, 32-byte messages, 10-second sustained load.

TCP Echo

Metric StormSocket NetCoreServer
Throughput 342 MiB/s 73 MiB/s
Messages/sec 11,205,120 2,386,789
Latency 89 ns 418 ns

WebSocket Echo

Metric StormSocket NetCoreServer
Throughput 66 MiB/s 40 MiB/s
Messages/sec 2,163,373 1,309,842
Latency 462 ns 763 ns

Results will vary by hardware. Benchmark projects under benchmark/ — run them yourself.

dotnet run -c Release --project benchmark/StormSocket.Benchmark.TcpEchoServer
dotnet run -c Release --project benchmark/StormSocket.Benchmark.TcpEchoClient -- -c 100 -m 1000 -s 32 -z 10

Documentation

Guide Description
Getting Started Installation, first TCP server, first WebSocket server
Examples TCP echo, WebSocket chat, auth, SSL, clients, admin console
Features Guide Sessions, groups, framing, heartbeat, slow consumer, rate limiting, fragmentation, disconnect reasons
Middleware Pipeline, custom middleware, built-in rate limiting
Configuration All options tables (ServerOptions, WebSocketOptions, ClientOptions, etc.)
API Reference INetworkSession, ISession, WebSocketSession, clients, middleware, framers
Architecture Connection lifecycle, write serialization, backpressure internals

Building

git clone https://github.com/suleymanbyzt/StormSocket.git
cd StormSocket
dotnet build
dotnet test

Samples

Sample Port Description
StormSocket.Samples.TcpEcho 5000 TCP echo server, test with telnet
StormSocket.Samples.WsChat 8080 WebSocket broadcast chat
StormSocket.Samples.SslEcho 5001 SSL/TLS echo with self-signed cert
StormSocket.Samples.WsServer 8080 Full-featured WS server with admin console, rooms, heartbeat
dotnet run --project samples/StormSocket.Samples.TcpEcho
dotnet run --project samples/StormSocket.Samples.WsChat
dotnet run --project samples/StormSocket.Samples.SslEcho
dotnet run --project samples/StormSocket.Samples.WsServer

License

MIT License - see LICENSE for details.

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 is compatible.  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 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 is compatible.  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 is compatible.  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
4.0.1 37 3/17/2026
4.0.0 132 3/11/2026
3.2.0 80 3/9/2026
3.1.1 81 3/8/2026
3.1.0 76 3/7/2026
3.0.0 76 3/7/2026
2.2.0 72 3/7/2026
2.1.0 82 3/6/2026
2.0.0 77 3/6/2026
1.1.4 75 3/5/2026
1.1.3 76 3/5/2026
1.1.2 82 3/4/2026
1.1.1 77 3/3/2026
1.1.0 75 3/3/2026
1.0.1 83 2/23/2026
1.0.0 102 2/10/2026
0.2.3 87 2/10/2026
0.2.2 88 2/9/2026
0.2.1 90 2/8/2026
0.2.0 94 2/8/2026
Loading failed