Skip to content
Projects

About

SAEA.Socket is a cross-platform, zero-copy, high-performance socket networking framework targeting .NET Standard 2.0, with implementations for IOCP, Epoll, and Kqueue. The Src directory contains numerous demos, including P2P, SOCKS5, WebSocket client and server, message queue, RPC, Redis driver, HTTP server, MQTT, MVC, DNS, and message server.

Systems & Infrastructure

How these counts are measured

Measured star growth

in 24h
0
in 7 days
0
in 15 days
0
in 1 month
Collecting history

Net star changes over overlapping periods, not daily totals. Missing measurements are left blank. Stars measure attention, not software quality.

README.en.md

Original

Logo SAEA - High-Performance Network Communication Framework Family 🚀

NuGet version (SAEA) License

English Version | 中文版

A cross-platform high-performance network communication framework based on .NET Standard 2.0. The underlying async IO mechanism is selected by the .NET runtime for the current OS (IOCP on Windows, epoll on Linux, kqueue on macOS); the send/receive path uses zero-copy (Span/Memory) and pooled buffers, providing complete network application solutions.

SAEA.Socket is a cross-platform high-performance sockets network framework. The Src directory contains its usage scenarios, such as large file transfer, WebSocket client and server, high-performance message queue, RPC, Redis driver, HTTP Server, MQTT, MVC, DNS, message server, etc.


Quick Navigation 🧭

Section Content
⚡ 30-Second Quick Start Easiest way to get started
🧩 Component Navigation Choose the right component
📐 Project Architecture Overall architecture design
✨ Core Features Key functionality highlights
📊 Implementation & Performance The two transports and measured-data notes
❓ FAQ Quick answers
🔗 Resource Links More learning resources

30-Second Quick Start ⚡

Option 1: Install Core Socket Framework

dotnet add package SAEA.Sockets
// Create a TCP server (only 5 lines of code)
var server = SocketFactory.CreateServerSocket(
    SocketOptionBuilder.Instance.SetSocket(SAEASocketType.Tcp).UsePacket().SetPort(39654).Build()
);
server.OnServerReceiveSpan += (userToken, data) => server.Send(userToken.ID, data);
server.Start();

💡 OnServerReceiveSpan's data is a ReadOnlySpan<byte> valid only during the callback; consume it synchronously inside the callback (or copy with ToArray()).

Option 2: Choose the Right Component for Your Needs

Select the appropriate component based on your requirements:

Your Needs Recommended Component Install Command
Web API Development SAEA.MVC dotnet add package SAEA.MVC
WebSocket Real-time Communication SAEA.WebSocket dotnet add package SAEA.WebSocket
P2P Punching and Relay SAEA.P2P dotnet add package SAEA.P2P
Redis Cache Operations SAEA.RedisSocket dotnet add package SAEA.RedisSocket
Microservice RPC SAEA.RPC dotnet add package SAEA.RPC
IoT Device Communication SAEA.MQTT dotnet add package SAEA.MQTT
File Transfer SAEA.FileSocket dotnet add package SAEA.FileSocket

Component Navigation 🧩

Core Components

Component Function NuGet 中文文档 English Docs Use Cases
🔌 SAEA.Sockets Cross-platform high-performance Socket framework NuGet 中文 English Game servers, real-time communication, IoT
🔧 SAEA.Common Common utility library NuGet 中文 English Serialization, caching, encryption
🧱 SAEA.Sockets.Pipeline Bidirectional channel pipeline with pluggable framing and two-level codecs NuGet 中文 English Protocol servers needing a handler chain, authentication, timeouts and backpressure

Certificate generation and format conversion: Src/SAEA.Sockets.SslTlsTool (includes openssl-compatible subcommands).

Web Application Components

Component Function NuGet 中文文档 English Docs Use Cases
🌐 SAEA.Http HTTP server NuGet 中文 English RESTful API, static file serving
🎨 SAEA.MVC MVC Web framework NuGet 中文 English Web applications, API services

Real-time Communication Components

Component Function NuGet 中文文档 English Docs Use Cases
💬 SAEA.WebSocket WebSocket server/client NuGet 中文 English Real-time chat, push notifications
🤖 SAEA.MQTT MQTT protocol implementation NuGet 中文 English IoT devices, smart home
📨 SAEA.MessageSocket Message server NuGet 中文 English Instant messaging, online customer service

P2P Communication Components

Component Function NuGet 中文文档 English Docs Use Cases
🔗 SAEA.P2P ICE-style punching + built-in STUN/TURN relay component NuGet 中文 English Direct connection through NAT, TURN relay fallback, LAN discovery, instant messaging, game battles

Data & Storage Components

Component Function NuGet 中文文档 English Docs Use Cases
📦 SAEA.RedisSocket Redis client NuGet 中文 English Redis cache, distributed lock
📁 SAEA.FileSocket File transfer component NuGet 中文 English Large file transfer, resumable upload
🗂️ SAEA.FTP FTP server/client NuGet 中文 English File servers, FTP clients

Distributed System Components

Component Function NuGet 中文文档 English Docs Use Cases
🔗 SAEA.RPC RPC remote invocation NuGet 中文 English Microservice communication, remote calls
📊 SAEA.QueueSocket In-memory message queue NuGet 中文 English Pub/Sub, event notifications

Network Utility Components

Component Function NuGet 中文文档 English Docs Use Cases
🌍 SAEA.DNS DNS server/client NuGet 中文 English DNS proxy, domain resolution
🔀 SAEA.Socket5 SOCKS5 proxy server/client NuGet 中文 English Forward proxy, intranet tunneling, UDP forwarding

Project Architecture 📐

SAEA Component Family Architecture

┌─────────────────────────────────────────────────────────────────┐
│                 SAEA Component Family Overview                   │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│   ┌───────────── Application Layer ─────────────┐               │
│   │                                              │               │
│   │  ┌─────────┐  ┌──────────┐                  │               │
│   │  │  MVC    │  │ WebSocket│                  │               │
│   │  │(Web)    │  │(Realtime)│                  │               │
│   │  └────┬────┘  └────┬─────┘                  │               │
│   │       │            │                         │               │
│   │  ┌────▼────┐  ┌───▼────┐  ┌─────────┐      │               │
│   │  │  RPC    │  │ MQTT   │  │ Message │      │               │
│   │  │(Remote) │  │ (IoT)  │  │ Socket  │      │               │
│   │  └────┬────┘  └───┬────┘  └────┬────┘      │               │
│   │       │           │            │            │               │
│   │  ┌────▼────┐  ┌───▼────┐       │            │               │
│   │  │  P2P    │  │ Redis  │       │            │               │
│   │  │(NAT)    │  │(Cache) │       │            │               │
│   │  └────┬────┘  └───┬────┘       │            │               │
│   │       │           │            │            │               │
│   └─────────┼───────────┼────────────┼──────────┘               │
│             │           │            │                           │
│   ┌─────────▼───────────▼────────────▼─────────┐               │
│   │           SAEA.Sockets (Core Layer)          │               │
│   │        Cross-Platform High-Perf Socket       │               │
│   │  ┌──────────┐  ┌──────────┐  ┌──────┐      │               │
│   │  │IocpSocket│  │StreamSock│  │UdpSock│      │               │
│   │  │ (TCP)    │  │(Stream)  │  │ (UDP) │      │               │
│   │  └──────────┘  └──────────┘  └──────┘      │               │
│   │  ┌──────────────────────────────────┐       │               │
│   │  │  BufferPool │ Session │  Coder   │       │               │
│   │  │  (Memory)   │(Session)│(Codec)   │       │               │
│   │  └──────────────────────────────────┘       │               │
│   └──────────────────┬────────────────────┘                   │
│                      │                                          │
│   ┌──────────────────▼────────────────────┐                   │
│   │         SAEA.Common (Base Layer)      │                   │
│   │    Common Utilities (Serialize/Cache/Encrypt)│             │
│   │  ┌────────┐  ┌───────┐  ┌───────┐    │                   │
│   │  │Serialize│  │ Cache │  │Encrypt│    │                   │
│   │  │  (Ser)  │  │(Cache)│  │(Enc)  │    │                   │
│   │  └────────┘  └───────┘  └───────┘    │                   │
│   └───────────────────────────────────────┘                   │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

Data Flow Architecture

Client Request Flow:

┌─────────┐      ┌──────────┐      ┌──────────┐
│ Client  │─────►│ Sockets  │─────►│  Coder   │
│(TCP/UDP)│      │Async Recv│      │  Decode  │
└─────────┘      └──────────┘      └──────────┘
                                          │
                                          ▼
                     ┌────────────────────────────────┐
                     │    Application Layer (Business) │
                     │  MVC / RPC / WebSocket / MQTT    │
                     └────────────────────────────────┘
                                          │
                                          ▼
                     ┌──────────┐      ┌──────────┐
                     │  Coder   │─────►│ Sockets  │─────► Client
                     │  Encode  │      │Async Send│
                     └──────────┘      └──────────┘

Core Features ✨

Feature Description
🚀 Cross-Platform Async IO The .NET runtime selects IOCP / epoll / kqueue automatically on Windows/Linux/macOS, behind one API
📦 Zero-Copy + Memory Pool Span/Memory zero-copy send/receive path; BufferManager, UserTokenPool and MemoryPoolManager reuse buffers, greatly reducing GC pressure
🔒 SSL/TLS Encryption Stream mode supports secure connections
🌐 IPv6 Support Full compatibility with IPv6 protocol
🔄 Session Management SessionManager automatically manages connection sessions
🛠️ Custom Protocol ICoder interface supports flexible protocol encoding/decoding
🔗 Fluent Configuration SocketOptionBuilder is concise and easy to use
📝 Complete Components MVC, WebSocket, RPC, Redis, MQTT, etc. covering all scenarios

Implementation & Performance 📊

The Two Transports

Transport How to select Best for
SocketAsyncEventArgs mode .UsePacket() High-throughput binary protocols, custom framing, UDP (UDP only works in this mode)
Pipelines stream mode .UseStream() SSL/TLS, or stream-style reads/writes through GetStream()

Both transports are cross-platform; the underlying IO mechanism is chosen by the .NET runtime (IOCP on Windows, epoll on Linux, kqueue on macOS). UsePacket() is the entry point for the SocketAsyncEventArgs transport and does not imply a Windows requirement.

Handler Pipelines in the Upper-Layer Components

Receive callbacks and connection lifecycle in Http, WebSocket, FileSocket, RPC, QueueSocket and MessageSocket are now handled by a SAEA.Sockets.Pipeline handler chain instead of OnMessage / OnDisconnected / OnErr style events. Append handlers before the pipeline is built through ConfigurePipeline:

using SAEA.MessageSocket;
using SAEA.Sockets.Pipeline;

var server = new MessageServer(port: 39654);

// Called once per connection with the connection id and the not-yet-started pipeline
server.ConfigurePipeline = (channelId, pipeline) => pipeline.AddLast(new MyInboundHandler());
server.Start();

Handlers derive from InboundHandlerAdapter: consume decoded messages in ChannelReadAsync, react to disconnects in ChannelInactiveAsync, and observe pipeline errors in ChannelExceptionCaughtAsync. Messages left unconsumed are recycled at the pipeline tail, while transport errors still flow into ExceptionCollector.

Assign the callback before Start() or the first Connect(); assigning it after the chain starts throws InvalidOperationException. Entry points that connect in their constructors, such as the RPC consumer and QueueSocket Producer, only accept the callback through their constructor.

Pipeline assembly contract and codecs

  • Startup validation: upper-layer components enable terminal-handler validation; Start() requires the last inbound node to be an ExceptionTerminalHandler and exactly one OutboundSerializingHandler at the rightmost end of the outbound prefix. Otherwise startup fails and the channel shuts down instead of running in a broken state.
  • Per-connection configuration: every connection creates its own pipeline options and splitter instance, never shared across connections. Once a splitter holds connection-level state (for example protocol switching), a shared instance would make connections interfere with each other.
  • Raw-byte outbound: to bypass the encoder and write bytes directly, use WriteAsync(new RawFrame(...)); both SendRaw in SAEA.Http and WebSocket sends in MVC take this path.
  • Codec entry points: WebSocket receive on the MVC side uses the WSCoder.Decode(byte[]) overload to avoid copying the whole message; ICoder.Decode(ReadOnlySequence<byte>) remains for other callers. The placeholder FTPCoder in SAEA.FTP has been removed; RedisCoder in SAEA.RedisSocket only serves as a generic constraint and throws NotSupportedException from Encode/Decode.

SAEA.RPC vs HTTP RPC

Feature SAEA.RPC HTTP RPC
Serialization Protobuf JSON
Transport Protocol TCP HTTP
Connection Mode Persistent Short-lived
Concurrency Model Async IO Blocking
Performance High Medium

Zero-Copy Receive Path (Measured)

Under the same send/receive benchmark, the span-based receive path of SAEA.Sockets dramatically cuts allocations and GC compared with the legacy decode path:

Path Throughput Allocation GC0
Legacy LegacyDecode 42,345 frames/s 4,662 B/frame 18
Zero-copy SpanDecodeStream 45,344 frames/s 34 B/frame 0

Data from SAEA.P2PTest --bench-iocp (4KB frames, single-machine loopback; numbers vary with hardware).

This README does not publish cross-framework performance numbers (for comparisons with TouchSocket, DotNetty, etc., benchmark your own workload).

End-to-end measurements (HTTP / WebSocket)

The full-stack benchmark of SAEA.MVC on top of SAEA.Http and SAEA.Sockets: client and server run in two separate processes over IPv4 loopback on one machine, and each of the six cases is the median of 3 runs:

Case RPS p50 / p99
HTTP serial (5,000 requests, short connections) 1,144 0.70 / 1.78 ms
HTTP 16 concurrent (10 s, short connections) 5,830 2.11 / 12.36 ms
HTTP 64 concurrent (10 s, short connections) 5,408 10.10 / 27.72 ms
HTTPS serial (2,000 requests, short connections) 203 4.51 / 8.13 ms
Static 100 KB serial (memory cache hit) 345 RPS / 33.7 MiB·s⁻¹ 2.51 / 4.41 ms
WebSocket single-connection echo 7,892 msg/s 0.12 / 0.22 ms

Scope: the whole set uses short connections (one TCP connection per request) and does not represent throughput under the default keep-alive; see the "Keep-alive benchmark (process-isolated)" and "Per-request allocation and CPU cost" sections of SAEA.MVC for those. HTTPS uses a self-signed certificate, TLS 1.2 fixed and certificate validation skipped; static files are served from the in-memory cache, so this is not the first-read or large-file path. The same probe varies 20%–35% between runs, so these numbers are only valid for relative comparison within one run, not as production absolutes.

Before the fix, both concurrency cases had 1–8 connections out of every 30,000–60,000 receive no response (showing up as unexpected EOF before response header or an RST at teardown). The table above was collected before the fix; after the connection-layer race was fixed (a disconnect left over from the previous connection closed a new connection whose token had already been reused), the same load generator completed 1,000,000 short connections at concurrency 64 / 128 / 256 with 0 no-response failures. The RPS denominator is the number of requests actually completed.

Full data, failure rates and resource usage (old versions, old methodology) are in the MVC / TLS acceptance record; component-level scopes are in the benchmark sections of SAEA.Http and SAEA.MVC. SAEA.Http has not been benchmarked separately as a stand-alone server.


FAQ ❓

Q1: What projects is SAEA suitable for?

A: SAEA is suitable for the following scenarios:

  • 🎮 Game servers (real-time battles, state synchronization)
  • 📊 Real-time data push (stock quotes, sports scores)
  • 🤖 IoT device communication (sensor data reporting)
  • 💬 Instant messaging (private chat, group chat, customer service systems)
  • 🔗 Microservice communication (RPC remote calls)
  • 📁 Large file transfer (resumable upload, high-speed transfer)
  • 🌐 P2P punching and relay (ICE-style punching, STUN/TURN relay, LAN discovery)

Q2: How to choose the right component?

A: Choose based on your needs:

Your Needs                        Recommended Component
─────────────────────────────────────────────
Web API Development         →  SAEA.MVC
Real-time Chat/Push         →  SAEA.WebSocket
P2P Punching and Relay      →  SAEA.P2P
IoT Device Communication    →  SAEA.MQTT
Redis Cache Operations      →  SAEA.RedisSocket
Microservice RPC            →  SAEA.RPC
File Transfer               →  SAEA.FileSocket
Custom Protocol             →  SAEA.Sockets

Q3: Is cross-platform supported?

A: Based on .NET Standard 2.0, Windows, Linux and macOS share the same API:

  • ✅ Windows (IOCP underneath)
  • ✅ Linux (epoll underneath)
  • ✅ macOS (kqueue underneath)

The mechanism is selected automatically by the .NET runtime; no conditional compilation or implementation switching is needed. UsePacket() is the entry point for the SocketAsyncEventArgs transport and does not imply a Windows requirement.

Q4: How to install via NuGet?

A: Search for "SAEA" or install directly:

# Package Manager
Install-Package SAEA.Sockets -Version 26.9.21.1

# .NET CLI
dotnet add package SAEA.Sockets --version 26.9.21.1

NuGet Link

Q5: How to get started quickly?

A: 3-step quick start:

  1. Install the NuGet package for the corresponding component
  2. Read the "30-Second Quick Start" section in the component's README
  3. Check the complete sample code

Each component has detailed usage examples and comments.

Q6: Are there sample projects?

A: The Src directory contains multiple test projects demonstrating real-world usage scenarios:

  • SAEA.Sockets.TcpTest / SAEA.Sockets.UdpTest / SAEA.Sockets.PipelineTest - Socket examples for the three transports
  • SAEA.WebSocketTest - WebSocket examples
  • SAEA.MVCTest - MVC Web application examples
  • SAEA.RedisSocketTest - Redis operations example
  • SAEA.RPCTest - RPC call examples
  • SAEA.P2PTest - STUN/TURN server host + P2P client self-test harness
  • SAEA.Sockets.SslTlsTool - Development SSL/TLS certificate generator and format converter (includes openssl-compatible subcommands)

Unit Test Projects: Src/*.Tests/ contains 11 MSTest projects, none of which are included in Src/SAEA.Sockets.sln, so run them individually as needed; they target net10.0. Example command: dotnet test Src/SAEA.Common.Tests/SAEA.Common.Tests.csproj -c Release

Projects: SAEA.Common.Tests, SAEA.MQTT.Tests, SAEA.FTP.Tests, SAEA.Http.Tests, SAEA.WebSocket.Tests, SAEA.FileSocket.Tests, SAEA.RPC.Tests, SAEA.QueueSocket.Tests, SAEA.MessageSocket.Tests, SAEA.P2P.Tests (requires the .NET 8 runtime), SAEA.MVC.Tests.


Screenshots 🖼️


Resource Links 🔗

Official Resources

Related Projects

  • WebRedisManager - Redis management tool based on SAEA.RedisSocket
  • SAEA.Rested - REST API example based on SAEA.MVC
  • GFF - QQ-like communication program based on SAEA

Support


License

Apache License 2.0

Explore related projects

Loading…