# Introduction
`rs-netty` 是一个 Tokio-native、Netty-inspired 的 Rust 网络框架。它保留了 Channel / Pipeline / Handler 这些熟悉的概念,但主路径建立在 Rust 类型系统、`async/await`、Tokio task、bounded channel queue 和普通 owned message 上。
当前 crate 根启用了 `#![deny(unsafe_code)]`,公开入口主要是:
- `pipeline()`:构建 TCP stream pipeline。
- `datagram_pipeline()`:构建 UDP datagram pipeline。
- `TcpServer` / `TcpClient`:运行 TCP server/client。
- `UdpServer` / `UdpClient`:运行 UDP server/client。
- `Handler` / `DatagramHandler` / `Inbound` / `Business` / `Outbound`:实现 pipeline stage。
- `Channel` / `DatagramChannel`:从 handler 外部写入、flush 或关闭连接/Socket。
- `Life`:可选 lifecycle hook。
- `#[handler]`:为简单 handler 生成 TCP 和 UDP final handler impl。
## Minimal TCP Server
这个例子贴近 `examples/tcp_echo_server.rs`:
```rust
use rs_netty::{codec::LineCodec, handler, pipeline, Result, TcpServer};
#[tokio::main]
async fn main() -> Result<()> {
TcpServer::bind("127.0.0.1:9000")
.pipeline(|| {
pipeline()
.codec(LineCodec::new())
.handler(Echo)
})
.run()
.await
}
struct Echo;
#[handler(Echo)]
async fn echo(msg: String) -> Result<String> {
Ok(msg)
}
```
`LineCodec` 把 TCP byte stream 解码成 `String`,`Echo` 收到 `String`,宏生成的 handler 会把返回的 `String` 通过 outbound side 写回并 flush。
## Minimal UDP Server
这个例子贴近 `examples/udp_echo_server.rs`:
```rust
use rs_netty::{codec::Utf8DatagramCodec, datagram_pipeline, handler, Result, UdpServer};
#[tokio::main]
async fn main() -> Result<()> {
UdpServer::bind("127.0.0.1:9002")
.pipeline(|| {
datagram_pipeline()
.codec(Utf8DatagramCodec)
.handler(UdpEcho)
})
.run()
.await
}
struct UdpEcho;
#[handler(UdpEcho)]
async fn udp_echo(msg: String) -> Result<String> {
Ok(format!("echo: {msg}"))
}
```
UDP pipeline 处理的是一个个完整 datagram。`DatagramContext::write` 默认回复当前 datagram 的 sender;如果要写给其他 peer,使用 `write_to` 或 `write_to_and_flush`。
## How To Read This Guide
如果你想使用框架,先看 `Typed Pipeline`、`TCP`、`UDP`、`Handlers`、`Codecs`。如果你要扩展框架,重点看 `Architecture`、`Lifecycle`、`Channel Write And Flush`、`Extension Guide` 和 `API Map`。