Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Examples

仓库的 examples 覆盖了 TCP、UDP、typed chain、JSON、TLS、lifecycle、HTTP 和 WebSocket。

TCP Echo

  • examples/tcp_echo_server.rs
  • examples/tcp_echo_client.rs

运行:

cargo run --example tcp_echo_server
cargo run --example tcp_echo_client

server 使用 LineCodec#[handler(Echo)],client 使用 write_and_flush 发送两行。

Typed TCP Chain

  • examples/tcp_typed_chain.rs
  • examples/tcp_typed_chain_client.rs

运行:

cargo run --example tcp_typed_chain
cargo run --example tcp_typed_chain_client

server pipeline:

#![allow(unused)]
fn main() {
pipeline()
    .codec(LineCodec::new())
    .inbound(Trim)
    .inbound(ParseRequest)
    .handler(Router)
    .outbound(RenderResponse)
}

这个例子展示 String -> Request -> Response -> String 的完整类型链。

JSON Over Line

  • examples/tcp_json_line_echo.rs

运行 server:

cargo run --example tcp_json_line_echo --features json

运行 client:

cargo run --example tcp_json_line_echo --features json -- client

这个例子把 framing 和 JSON 分开:LineCodec 负责行边界,JsonDecode<T> / JsonEncode<T> 负责 typed JSON。

TLS Echo

  • examples/tcp_tls_echo.rs

运行:

cargo run --example tcp_tls_echo --features tls

这个例子生成 localhost 测试证书,通过 .tls(...) 挂到 TCP transport 上,同时继续把 LineCodec 作为应用明文 codec。 同一组 TLS context API 也支持 required 或 optional mTLS、ALPN 发布、SNI-specific certificate identities,以及通过 TCP handler/stage context 读取 TlsInfo metadata。

Lifecycle

  • examples/tcp_lifecycle.rs

运行:

cargo run --example tcp_lifecycle

这个例子实现 Life,打印 TCP server started/stopped 和 connection opened/closed。

UDP Echo

  • examples/udp_echo_server.rs
  • examples/udp_echo_client.rs

运行:

cargo run --example udp_echo_server
cargo run --example udp_echo_client

使用 Utf8DatagramCodecdatagram_pipeline()

Typed UDP Chain

  • examples/udp_typed_chain.rs
  • examples/udp_typed_chain_client.rs

运行:

cargo run --example udp_typed_chain
cargo run --example udp_typed_chain_client

展示 UDP datagram pipeline 的 typed inbound/outbound 转换。

HTTP And WebSocket

  • examples/http_server.rs
  • examples/websocket_server.rs
  • examples/http_websocket_server.rs

运行:

cargo run --example http_server
cargo run --example websocket_server --features websocket
cargo run --example http_websocket_server --features websocket

http_server 使用 HttpCodecwebsocket_server 使用 WebSocketCodechttp_websocket_server 使用 HttpWsCodecHttpWsRouter 在同一个 port 上处理 HTTP request 与 WebSocket upgrade。