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

Lifecycle

Life 是可选 lifecycle hook trait。默认实现是 NoLife,所有方法 no-op。

#![allow(unused)]
fn main() {
#[derive(Clone, Copy)]
struct PrintLife;

impl rs_netty::Life for PrintLife {
    async fn tcp_server_started(&self, local_addr: std::net::SocketAddr) -> rs_netty::Result<()> {
        println!("server started: {local_addr}");
        Ok(())
    }
}
}

Hooks

当前 hooks:

  • tcp_server_started(local_addr)
  • tcp_server_stopped(local_addr)
  • tcp_connection_opened(info)
  • tcp_connection_closed(info, reason)
  • udp_socket_started(local_addr)
  • udp_socket_stopped(local_addr)

TCP connection close reason 使用 CloseReason,包括 PeerClosedLocalClosedChannelClosedHandlerClosedServerShutdownIdleTimeoutIoErrorDecodeErrorEncodeErrorFrameTooLargeHandlerError

Startup And Shutdown Behavior

TCP server start() 绑定 listener 后调用 tcp_server_started。如果该 hook 返回错误,start() 返回错误。

每个 TCP connection accepted 或 client connected 后调用 tcp_connection_opened。如果该 hook 失败,连接任务返回错误。

关闭时的 hook 失败会记录日志,并尽量保留原始关闭结果。

UDP socket task 启动时调用 udp_socket_started,停止时调用 udp_socket_stopped

Graceful Shutdown

TCP/UDP server 的 start() 返回 handle:

#![allow(unused)]
fn main() {
let server = TcpServer::bind("127.0.0.1:0")
    .pipeline(|| pipeline().codec(LineCodec::new()).handler(Echo))
    .start()
    .await?;

server.shutdown();
server.wait().await?;
Ok::<(), rs_netty::Error>(())
}

TCP server shutdown 使用 watch channel 通知 accept loop 和 connection tasks。UDP server shutdown 通知 socket task 退出。

client 没有 server shutdown handle,使用 client.close().await? 请求本地 connection/socket task 关闭,然后 client.wait().await? 等待任务结束。

Idle Timeout

TCP 支持 idle_timeout(duration)。它关闭一段时间内没有 socket read 的连接,并以 CloseReason::IdleTimeout 通知 lifecycle hook。源码中的 timeout 只在 read 成功后 reset;纯 outbound 写不会 reset 这个 read-idle timer。

UDP 当前没有 idle timeout。

Connection Stats

TCP server/client 可以通过 track_connection_stats() 启用 stats。启用后:

  • Context::stats() 返回当前连接的 ConnectionStats
  • Channel::stats() 返回 cloneable stats handle。
  • 统计包括 connected_atbytes_readbytes_writtenframes_readframes_written

stats 默认关闭,避免不需要监控时产生额外 shared allocation 和 atomic update。