{"id":24167619,"url":"https://github.com/zoujiaqing/msgtrans","last_synced_at":"2026-02-22T21:55:59.608Z","repository":{"id":252561268,"uuid":"840786124","full_name":"zoujiaqing/msgtrans","owner":"zoujiaqing","description":"MsgTrans for rust, support multiple protocol create server and client, protocol support Tcp / WebSocket / QUIC.","archived":false,"fork":false,"pushed_at":"2026-02-18T11:40:13.000Z","size":1205,"stargazers_count":59,"open_issues_count":0,"forks_count":7,"subscribers_count":4,"default_branch":"main","last_synced_at":"2026-02-18T15:53:30.308Z","etag":null,"topics":["network","quic","quic-client","quic-server","socket","tcp","tcp-client","tcp-server","websocket","websocket-client","websocket-server"],"latest_commit_sha":null,"homepage":"","language":"Rust","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/zoujiaqing.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2024-08-10T17:18:08.000Z","updated_at":"2026-02-18T11:40:16.000Z","dependencies_parsed_at":"2024-11-11T20:24:19.639Z","dependency_job_id":"8d024e4d-c593-41c0-aad5-8d091b0b3e09","html_url":"https://github.com/zoujiaqing/msgtrans","commit_stats":null,"previous_names":["zoujiaqing/msgtrans-rust","zoujiaqing/msgtrans"],"tags_count":5,"template":false,"template_full_name":null,"purl":"pkg:github/zoujiaqing/msgtrans","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zoujiaqing%2Fmsgtrans","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zoujiaqing%2Fmsgtrans/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zoujiaqing%2Fmsgtrans/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zoujiaqing%2Fmsgtrans/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/zoujiaqing","download_url":"https://codeload.github.com/zoujiaqing/msgtrans/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/zoujiaqing%2Fmsgtrans/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29728540,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-22T20:09:16.275Z","status":"ssl_error","status_checked_at":"2026-02-22T20:09:13.750Z","response_time":110,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["network","quic","quic-client","quic-server","socket","tcp","tcp-client","tcp-server","websocket","websocket-client","websocket-server"],"created_at":"2025-01-12T21:47:15.166Z","updated_at":"2026-02-22T21:55:59.578Z","avatar_url":"https://github.com/zoujiaqing.png","language":"Rust","funding_links":[],"categories":[],"sub_categories":[],"readme":"# 🚀 MsgTrans - Modern Multi-Protocol Communication Framework\n\n[![Rust](https://img.shields.io/badge/rust-1.80+-orange.svg)](https://www.rust-lang.org)\n[![License](https://img.shields.io/badge/license-Apache-blue.svg)](LICENSE)\n[![Version](https://img.shields.io/badge/version-1.0.0--beta.1-green.svg)](Cargo.toml)\n\n🌐 Language: [English](README.md) | [简体中文](README.zh-CN.md)\n\n\u003e **Enterprise-grade modern multi-protocol communication framework with unified interface supporting TCP, WebSocket, QUIC and more**\n\n## 🌟 Core Features\n\n### ⚡ Ultimate Performance\n - **1M+** concurrent connections support\n - **10M+/sec** message throughput\n - **1ms** average latency\n - **Lock-free concurrent architecture** fully utilizing multi-core performance\n\n### 🏗️ **Unified Architecture Design**\n- **Three-layer architecture abstraction**: Application → Transport → Protocol layers with clear separation\n- **Protocol-agnostic business logic**: One codebase, multi-protocol deployment\n- **Configuration-driven design**: Switch protocols through configuration without modifying business logic\n- **Hot-pluggable extensions**: Easily extend new protocol support\n\n### ⚡ **Modern Concurrent Architecture**\n- **Lock-free concurrent design**: Completely eliminate lock contention, fully utilize multi-core performance\n- **Zero-copy optimization**: `SharedPacket` and `ArcPacket` implement memory zero-copy\n- **Event-driven model**: Fully asynchronous non-blocking, efficient event handling\n- **Intelligent optimization**: CPU-aware automatic performance tuning\n\n### 🔌 **Multi-Protocol Unified Support**\n- **TCP** - Reliable transport protocol\n- **WebSocket** - Real-time Web communication\n- **QUIC** - Next-generation transport protocol\n- **Custom protocols** - Easily implement custom protocol extensions\n\n### 🎯 **Minimalist API Design**\n- **Builder pattern**: Fluent configuration, elegant and readable code\n- **Type safety**: Compile-time error checking, runtime stability and reliability\n- **Zero-configuration optimization**: High performance by default, ready to use out of the box\n- **Backward compatibility**: Zero migration cost for version upgrades\n\n## 🚀 Quick Start\n\n### Installation\n\n```toml\n[dependencies]\nmsgtrans = \"1.0.0\"\n```\n\n### Create Multi-Protocol Server\n\n```rust\nuse msgtrans::{\n    transport::TransportServerBuilder,\n    protocol::{TcpServerConfig, WebSocketServerConfig, QuicServerConfig},\n    event::ServerEvent,\n    tokio,\n};\n\n#[tokio::main]\nasync fn main() -\u003e Result\u003c(), Box\u003cdyn std::error::Error\u003e\u003e {\n    // Configure multiple protocols - same business logic supports multiple protocols\n    let tcp_config = TcpServerConfig::new(\"127.0.0.1:8001\")?;\n    \n    let websocket_config = WebSocketServerConfig::new(\"127.0.0.1:8002\")?\n        .with_path(\"/ws\");\n    \n    let quic_config = QuicServerConfig::new(\"127.0.0.1:8003\")?;\n\n    // Build multi-protocol server\n    let mut server = TransportServerBuilder::new()\n        .max_connections(10000)\n        .with_protocol(tcp_config)\n        .with_protocol(websocket_config)\n        .with_protocol(quic_config)\n        .build()\n        .await?;\n\n    println!(\"🚀 Multi-protocol server started successfully!\");\n    \n    // Get event stream\n    let mut events = server.events().await?;\n    \n    // Unified event handling - all protocols use the same logic\n    while let Some(event) = events.recv().await {\n        match event {\n            ServerEvent::ConnectionEstablished { session_id, .. } =\u003e {\n                println!(\"New connection: {}\", session_id);\n            }\n            ServerEvent::MessageReceived { session_id, context } =\u003e {\n                // Echo message - protocol transparent\n                let message = String::from_utf8_lossy(\u0026context.data);\n                let response = format!(\"Echo: {}\", message);\n                let _ = server.send(session_id, response.as_bytes()).await;\n            }\n            ServerEvent::ConnectionClosed { session_id, .. } =\u003e {\n                println!(\"Connection closed: {}\", session_id);\n            }\n            _ =\u003e {}\n        }\n    }\n\n    Ok(())\n}\n```\n\n### Create Client Connection\n\n```rust\nuse msgtrans::{\n    transport::TransportClientBuilder,\n    protocol::TcpClientConfig,\n    event::ClientEvent,\n    tokio,\n};\nuse std::time::Duration;\n\n#[tokio::main]\nasync fn main() -\u003e Result\u003c(), Box\u003cdyn std::error::Error\u003e\u003e {\n    // Configure client - configuration-driven protocol selection\n    let tcp_config = TcpClientConfig::new(\"127.0.0.1:8001\")?\n        .with_timeout(Duration::from_secs(30));\n\n    // Build client - zero configuration with high performance\n    let mut client = TransportClientBuilder::new()\n        .with_protocol(tcp_config)\n        .build()\n        .await?;\n\n    // Connect to server\n    client.connect().await?;\n\n    // Send message - simple API, directly send byte data\n    let _result = client.send(\"Hello, MsgTrans!\".as_bytes()).await?;\n    println!(\"✅ Message sent successfully\");\n\n    // Send request and wait for response\n    match client.request(\"What time is it?\".as_bytes()).await? {\n        result if result.data.is_some() =\u003e {\n            let response = String::from_utf8_lossy(result.data.as_ref().unwrap());\n            println!(\"📥 Received response: {}\", response);\n        }\n        _ =\u003e println!(\"❌ Request timeout or failed\"),\n    }\n\n    // Receive events - unified event model\n    let mut events = client.events().await?;\n    tokio::spawn(async move {\n        while let Some(event) = events.recv().await {\n            match event {\n                ClientEvent::MessageReceived(context) =\u003e {\n                    let message = String::from_utf8_lossy(\u0026context.data);\n                    println!(\"📨 Received message: {}\", message);\n                }\n                ClientEvent::Disconnected { .. } =\u003e {\n                    println!(\"🔌 Connection closed\");\n                    break;\n                }\n                _ =\u003e {}\n            }\n        }\n    });\n\n    Ok(())\n}\n```\n\n## 🏗️ Architecture Design\n\n### 📚 Three-Layer Architecture\n\n```\n┌─────────────────────────────────────┐\n│  🎯 Application Layer               │  ← Business logic, protocol-agnostic\n├─────────────────────────────────────┤\n│  🚀 Transport Layer                 │  ← Connection management, unified API\n│  ├── TransportServer/Client         │    • Connection lifecycle management\n│  ├── SessionManager                 │    • Event routing and dispatching\n│  └── EventStream                    │    • Message passing and broadcasting\n├─────────────────────────────────────┤\n│  📡 Protocol Layer                  │  ← Protocol implementation, extensible\n│  ├── TCP/WebSocket/QUIC             │    • Protocol-specific adapters\n│  ├── ProtocolAdapter                │    • Protocol configuration management\n│  └── ConfigurationRegistry          │    • Protocol registration mechanism\n└─────────────────────────────────────┘\n```\n\n### 🔄 Design Principles\n\n#### **Unified Abstraction, Protocol Transparency**\n- **TransportServer/Client** provide unified business interfaces\n- **Transport** manages single connection lifecycle\n- **ProtocolAdapter** hides protocol implementation details\n\n#### **Configuration-Driven, Flexible Extension**\n```rust\n// Same server code, different protocol configurations\nlet server = TransportServerBuilder::new()\n    .with_protocol(TcpServerConfig::new(\"0.0.0.0:8080\")?)\n    .build().await?;  // TCP version\n\nlet server = TransportServerBuilder::new()\n    .with_protocol(QuicServerConfig::new(\"0.0.0.0:8080\")?)\n    .build().await?;  // QUIC version - identical business logic\n```\n\n### 🎯 Event-Driven Model\n\n```rust\n// Server event types\npub enum ServerEvent {\n    ConnectionEstablished { session_id: SessionId, info: ConnectionInfo },\n    MessageReceived { session_id: SessionId, context: TransportContext },\n    MessageSent { session_id: SessionId, message_id: u32 },\n    ConnectionClosed { session_id: SessionId, reason: CloseReason },\n    TransportError { session_id: Option\u003cSessionId\u003e, error: TransportError },\n}\n\n// Client event types\npub enum ClientEvent {\n    Connected { info: ConnectionInfo },\n    MessageReceived(TransportContext),\n    MessageSent { message_id: u32 },\n    Disconnected { reason: CloseReason },\n    Error { error: TransportError },\n}\n\n// Concise event handling pattern - Server\nlet mut events = server.events().await?;\nwhile let Some(event) = events.recv().await {\n    match event {\n        ServerEvent::MessageReceived { session_id, context } =\u003e {\n            // Protocol-agnostic business processing - directly use byte data\n            let message = String::from_utf8_lossy(\u0026context.data);\n            let response = format!(\"Processing result: {}\", message);\n            server.send(session_id, response.as_bytes()).await?;\n        }\n        _ =\u003e {}\n    }\n}\n\n// Concise event handling pattern - Client\nlet mut events = client.events().await?;\nwhile let Some(event) = events.recv().await {\n    match event {\n        ClientEvent::MessageReceived(context) =\u003e {\n            // Handle received messages - directly use byte data\n            let message = String::from_utf8_lossy(\u0026context.data);\n            println!(\"Received: {}\", message);\n        }\n        _ =\u003e {}\n    }\n}\n```\n\n## ⚡ Modern Features\n\n### 🔒 Lock-Free Concurrent Architecture\n\n```rust\n// User-level API is simple, underlying automatic lock-free optimization\n// Concurrent sending - internally optimized with lock-free queues\nlet tasks: Vec\u003c_\u003e = (0..1000).map(|i| {\n    let client = client.clone();\n    tokio::spawn(async move {\n        let message = format!(\"Message {}\", i);\n        client.send(message.as_bytes()).await\n    })\n}).collect();\n\n// Server high-concurrency processing - internally using lock-free hash tables for session management\nlet mut events = server.events().await?;\nwhile let Some(event) = events.recv().await {\n    match event {\n        ServerEvent::MessageReceived { session_id, context } =\u003e {\n            // High-concurrency processing, lock-free session access\n            tokio::spawn(async move {\n                let response = process_message(\u0026context.data).await;\n                server.send(session_id, \u0026response).await\n            });\n        }\n        _ =\u003e {}\n    }\n}\n```\n\n### 🧠 Intelligent Optimization\n\n```rust\n// CPU-aware automatic optimization - zero configuration high performance\nlet config = ConnectionConfig::auto_optimized(); // Auto-tuning based on CPU core count\n\n// Intelligent connection pool - adaptive load\nlet server = TransportServerBuilder::new()\n    .connection_pool_config(\n        ConnectionPoolConfig::adaptive()  // Dynamic scaling\n            .with_initial_size(100)\n            .with_max_size(10000)\n    )\n    .build().await?;\n```\n\n### 📦 Zero-Copy Optimization\n\n```rust\n// User API always simple - internal automatic zero-copy optimization\nlet result = client.send(\"Hello, World!\".as_bytes()).await?;\n\n// Large data transmission - automatic zero-copy handling\nlet large_data = vec![0u8; 1024 * 1024]; // 1MB data\nlet result = client.send(\u0026large_data).await?;\n\n// Request-response - automatic zero-copy optimization\nlet response = client.request(b\"Get user data\").await?;\nif let Some(data) = response.data {\n    // Data transmission process already optimized, no additional copying needed\n    process_response(\u0026data);\n}\n```\n\n## 🔌 Protocol Extension\n\n### Implement Custom Protocol\n\n```rust\n// 1. Implement protocol adapter\npub struct MyProtocolAdapter {\n    connection: MyConnection,\n    event_sender: broadcast::Sender\u003cTransportEvent\u003e,\n}\n\n#[async_trait]\nimpl ProtocolAdapter for MyProtocolAdapter {\n    async fn send(\u0026mut self, packet: Packet) -\u003e Result\u003c(), TransportError\u003e {\n        // Implement protocol-specific send logic\n        self.connection.send(packet.payload()).await?;\n        Ok(())\n    }\n    \n    fn connection_info(\u0026self) -\u003e ConnectionInfo {\n        // Return connection information\n        ConnectionInfo::new(\"MyProtocol\", self.connection.peer_addr())\n    }\n    \n    fn events(\u0026self) -\u003e broadcast::Receiver\u003cTransportEvent\u003e {\n        self.event_sender.subscribe()\n    }\n}\n\n// 2. Implement configuration structure\n#[derive(Debug, Clone)]\npub struct MyProtocolServerConfig {\n    pub bind_address: SocketAddr,\n    pub custom_setting: String,\n}\n\n#[async_trait]\nimpl ServerConfig for MyProtocolServerConfig {\n    type Adapter = MyProtocolAdapter;\n    \n    async fn build_server(\u0026self) -\u003e Result\u003cSelf::Adapter, TransportError\u003e {\n        // Build server adapter\n        let connection = MyConnection::bind(\u0026self.bind_address).await?;\n        let (event_sender, _) = broadcast::channel(1000);\n        \n        Ok(MyProtocolAdapter {\n            connection,\n            event_sender,\n        })\n    }\n}\n\n// 3. Seamless integration - exactly the same usage as built-in protocols\nlet my_config = MyProtocolServerConfig {\n    bind_address: \"127.0.0.1:9000\".parse()?,\n    custom_setting: \"custom_value\".to_string(),\n};\n\nlet server = TransportServerBuilder::new()\n    .with_protocol(my_config)  // Use directly!\n    .build()\n    .await?;\n```\n\n## 📖 Usage Examples\n\n### 🌐 WebSocket Chat Server\n\n```rust\nuse msgtrans::{\n    transport::TransportServerBuilder,\n    protocol::WebSocketServerConfig,\n    event::ServerEvent,\n    SessionId,\n    tokio,\n};\nuse std::collections::HashMap;\n\n#[tokio::main]\nasync fn main() -\u003e Result\u003c(), Box\u003cdyn std::error::Error\u003e\u003e {\n    let config = WebSocketServerConfig::new(\"127.0.0.1:8080\")?\n        .with_path(\"/chat\");\n\n    let server = TransportServerBuilder::new()\n        .with_protocol(config)\n        .max_connections(1000)\n        .build()\n        .await?;\n\n    println!(\"🌐 WebSocket Chat Server: ws://127.0.0.1:8080/chat\");\n\n    // Chat room management\n    let mut chat_rooms: HashMap\u003cString, Vec\u003cSessionId\u003e\u003e = HashMap::new();\n    let mut events = server.events().await?;\n\n    while let Some(event) = events.recv().await {\n        match event {\n            ServerEvent::MessageReceived { session_id, context } =\u003e {\n                let message = String::from_utf8_lossy(\u0026context.data);\n                \n                // Parse chat commands\n                if message.starts_with(\"/join \") {\n                    let room = message[6..].to_string();\n                    chat_rooms.entry(room.clone()).or_default().push(session_id);\n                    \n                    let response = format!(\"Joined room: {}\", room);\n                    let _ = server.send(session_id, response.as_bytes()).await;\n                } else {\n                    // Broadcast message to all users in the room\n                    for (room, members) in \u0026chat_rooms {\n                        if members.contains(\u0026session_id) {\n                            let broadcast_msg = format!(\"[{}] {}\", room, message);\n                            for \u0026member_id in members {\n                                let _ = server.send(member_id, broadcast_msg.as_bytes()).await;\n                            }\n                            break;\n                        }\n                    }\n                }\n            }\n            ServerEvent::ConnectionClosed { session_id, .. } =\u003e {\n                // Remove user from all rooms\n                for members in chat_rooms.values_mut() {\n                    members.retain(|\u0026id| id != session_id);\n                }\n            }\n            _ =\u003e {}\n        }\n    }\n\n    Ok(())\n}\n```\n\n### ⚡ High-Performance QUIC Client\n\n```rust\nuse msgtrans::{\n    transport::TransportClientBuilder,\n    protocol::QuicClientConfig,\n    tokio,\n};\nuse std::time::Instant;\n\n#[tokio::main]\nasync fn main() -\u003e Result\u003c(), Box\u003cdyn std::error::Error\u003e\u003e {\n    let config = QuicClientConfig::new(\"127.0.0.1:8003\")?\n        .with_server_name(\"localhost\")\n        .with_alpn(vec![b\"msgtrans\".to_vec()]);\n\n    let client = TransportClientBuilder::new()\n        .with_protocol(config)\n        .build()\n        .await?;\n\n    client.connect().await?;\n    println!(\"✅ QUIC connection established successfully\");\n\n    // High-concurrency message sending test\n    let start = Instant::now();\n    let message_count = 10000;\n    \n    let tasks: Vec\u003c_\u003e = (0..message_count).map(|i| {\n        let client = client.clone();\n        tokio::spawn(async move {\n            let message = format!(\"High-performance message {}\", i);\n            client.send(message.as_bytes()).await\n        })\n    }).collect();\n\n    // Wait for all messages to complete sending\n    for task in tasks {\n        task.await??;\n    }\n\n    let duration = start.elapsed();\n    println!(\"🚀 {} messages sent, time elapsed: {:?}\", message_count, duration);\n    println!(\"📊 Average per second: {:.0} messages\", message_count as f64 / duration.as_secs_f64());\n\n    // Test request-response performance\n    let start = Instant::now();\n    let request_count = 1000;\n    \n    for i in 0..request_count {\n        let request_data = format!(\"Request {}\", i);\n        match client.request(request_data.as_bytes()).await? {\n            result if result.data.is_some() =\u003e {\n                // Request successful, record response time\n                if i % 100 == 0 {\n                    println!(\"✅ Request {} completed\", i);\n                }\n            }\n            _ =\u003e println!(\"❌ Request {} timeout\", i),\n        }\n    }\n    \n    let duration = start.elapsed();\n    println!(\"🔄 {} requests completed, time elapsed: {:?}\", request_count, duration);\n    println!(\"📊 Average per second: {:.0} requests\", request_count as f64 / duration.as_secs_f64());\n\n    Ok(())\n}\n```\n\n## 🛠️ Configuration Options\n\n### Server Configuration\n\n```rust\n// TCP Server - High reliability configuration\nlet tcp_config = TcpServerConfig::new(\"0.0.0.0:8001\")?\n    .with_max_connections(10000)\n    .with_keepalive(Duration::from_secs(60))\n    .with_nodelay(true)\n    .with_reuse_addr(true);\n\n// WebSocket Server - Web integration configuration\nlet ws_config = WebSocketServerConfig::new(\"0.0.0.0:8002\")?\n    .with_path(\"/api/ws\")\n    .with_max_frame_size(1024 * 1024)\n    .with_max_connections(5000);\n\n// QUIC Server - Next-generation protocol configuration\nlet quic_config = QuicServerConfig::new(\"0.0.0.0:8003\")?\n    .with_cert_path(\"cert.pem\")\n    .with_key_path(\"key.pem\")\n    .with_alpn(vec![b\"h3\".to_vec(), b\"msgtrans\".to_vec()])\n    .with_max_concurrent_streams(1000);\n```\n\n### Intelligent Configuration\n\n```rust\n// Zero configuration - automatic optimization (recommended)\nlet server = TransportServerBuilder::new()\n    .with_protocol(tcp_config)\n    .build().await?;  // Automatically optimized based on CPU\n\n// High-performance configuration - manual tuning\nlet server = TransportServerBuilder::new()\n    .with_protocol(tcp_config)\n    .connection_config(ConnectionConfig::high_performance())\n    .max_connections(50000)\n    .build().await?;\n\n// Resource-saving configuration - low memory environment\nlet server = TransportServerBuilder::new()\n    .with_protocol(tcp_config)\n    .connection_config(ConnectionConfig::memory_optimized())\n    .max_connections(1000)\n    .build().await?;\n```\n\n## 🔧 Advanced Features\n\n### 📊 Built-in Monitoring\n\n```rust\n// Real-time statistics - zero-copy performance monitoring\nlet stats = server.get_stats().await;\nprintln!(\"Active connections: {}\", stats.active_connections);\nprintln!(\"Total messages: {}\", stats.total_messages);\nprintln!(\"Average latency: {:?}\", stats.average_latency);\nprintln!(\"Memory usage: {} MB\", stats.memory_usage_mb);\n\n// Protocol distribution statistics\nfor (protocol, count) in \u0026stats.protocol_distribution {\n    println!(\"{}: {} connections\", protocol, count);\n}\n```\n\n### 🛡️ Graceful Error Handling\n\n```rust\nuse msgtrans::error::{TransportError, CloseReason};\n\n// Message sending error handling\nmatch client.send(\"Hello, World!\".as_bytes()).await {\n    Ok(result) =\u003e println!(\"✅ Message sent successfully (ID: {})\", result.message_id),\n    Err(TransportError::ConnectionLost { .. }) =\u003e {\n        println!(\"🔗 Connection lost, attempting reconnection\");\n        client.connect().await?;\n    }\n    Err(TransportError::ProtocolError { protocol, error }) =\u003e {\n        println!(\"⚠️ Protocol error [{}]: {}\", protocol, error);\n    }\n    Err(e) =\u003e println!(\"❌ Other error: {}\", e),\n}\n\n// Request-response error handling\nmatch client.request(\"Get status\".as_bytes()).await {\n    Ok(result) =\u003e {\n        match result.data {\n            Some(data) =\u003e {\n                let response = String::from_utf8_lossy(\u0026data);\n                println!(\"📥 Received response: {}\", response);\n            }\n            None =\u003e println!(\"⏰ Request timeout (ID: {})\", result.message_id),\n        }\n    }\n    Err(TransportError::Timeout { duration }) =\u003e {\n        println!(\"⏰ Request timeout: {:?}\", duration);\n    }\n    Err(e) =\u003e println!(\"❌ Request failed: {}\", e),\n}\n\n// Server-side sending error handling\nmatch server.send(session_id, \"Response data\".as_bytes()).await {\n    Ok(result) =\u003e println!(\"✅ Successfully sent to session {}\", session_id),\n    Err(TransportError::ConnectionLost { .. }) =\u003e {\n        println!(\"🔗 Session {} connection disconnected\", session_id);\n        // Automatic session cleanup\n    }\n    Err(e) =\u003e println!(\"❌ Send failed: {}\", e),\n}\n```\n\n### 🔄 Connection Management\n\n```rust\n// Connection pool management\nlet pool_config = ConnectionPoolConfig::adaptive()\n    .with_initial_size(100)\n    .with_max_size(10000)\n    .with_idle_timeout(Duration::from_secs(300))\n    .with_health_check_interval(Duration::from_secs(30));\n\n// Graceful shutdown\nlet server = TransportServerBuilder::new()\n    .with_protocol(tcp_config)\n    .graceful_shutdown_timeout(Duration::from_secs(30))\n    .build().await?;\n\n// Smooth restart support\nserver.start_graceful_shutdown().await?;\n```\n\n## 📚 Documentation and Examples\n\n### 📖 Complete Examples\n\nCheck the `examples/` directory for more examples:\n\n- [`echo_server.rs`](examples/echo_server.rs) - Multi-protocol echo server\n- [`echo_client_tcp.rs`](examples/echo_client_tcp.rs) - TCP client example\n- [`echo_client_websocket.rs`](examples/echo_client_websocket.rs) - WebSocket client example\n- [`echo_client_quic.rs`](examples/echo_client_quic.rs) - QUIC client example\n- [`packet.rs`](examples/packet.rs) - Packet serialization verification example\n\n### 🚀 Running Examples\n\n```bash\n# Start multi-protocol echo server\ncargo run --example echo_server\n\n# Test TCP client\ncargo run --example echo_client_tcp\n\n# Test WebSocket client  \ncargo run --example echo_client_websocket\n\n# Test QUIC client\ncargo run --example echo_client_quic\n```\n\n## 🏆 Use Cases\n\n- **🎮 Game Servers** - High-concurrency real-time game communication\n- **💬 Chat Systems** - Multi-protocol instant messaging platforms\n- **🔗 Microservice Communication** - Efficient inter-service data transmission\n- **📊 Real-time Data** - Financial, monitoring and other real-time systems\n- **🌐 IoT Platforms** - Large-scale device connection management\n- **🚪 Protocol Gateways** - Multi-protocol conversion and proxying\n\n## 📝 License\n\nThis project is licensed under the [Apache License 2.0](LICENSE).\n\nCopyright © 2024 [Jiaqing Zou](mailto:zoujiaqing@gmail.com)\n\n## 🤝 Contributing\n\nIssues and Pull Requests are welcome! Please check the [Contributing Guide](CONTRIBUTING.md) for detailed information.\n\n---\n\n\u003e 🎯 **MsgTrans Mission**: Make multi-protocol communication simple, efficient, and reliable, focusing on business logic rather than underlying transport details. ","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzoujiaqing%2Fmsgtrans","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fzoujiaqing%2Fmsgtrans","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fzoujiaqing%2Fmsgtrans/lists"}