Expand description
TCP server and client implementations with lockfree connection management.
This module provides high-performance TCP networking built on Mill-IO’s event loop.
Each TCP connection is assigned a unique ConnectionId generated atomically. The connection state is stored in a lockfree map, allowing concurrent access from multiple worker threads without blocking.
Connection Storage:
LockfreeMap<u64, TcpConnection>
│
├--> ConnId(1) --> TcpConnection { stream, token, addr }
├--> ConnId(2) --> TcpConnection { stream, token, addr }
└--> ConnId(N) --> TcpConnection { stream, token, addr }§Event Handling Pipeline
1. Listener Events:
New Connection --> TcpListenerHandler::handle_event()
- accept() --> Create ConnectionId
- Register TcpConnectionHandler with EventLoop
- Insert into LockfreeMap
- Call handler.on_connect()
2. Connection Events:
Readable Event --> TcpConnectionHandler::handle_event()
- Read from stream into pooled buffer
- Call handler.on_data()
- If EOF: disconnect()
Writable Event --> TcpConnectionHandler::handle_event()
- Call handler.on_writable()
3. Disconnection:
disconnect() --> Remove from LockfreeMap
- Deregister from EventLoop
- Call handler.on_disconnect()§Configuration
TcpServerConfig uses the builder pattern for ergonomic configuration:
use mill_net::tcp::config::TcpServerConfig;
let config = TcpServerConfig::builder()
.address("0.0.0.0:8080".parse().unwrap())
.buffer_size(16384) // Larger buffers for high throughput
.max_connections(1000) // Limit concurrent connections
.no_delay(true) // Disable Nagle's algorithm
.build();§Handler Implementation
Your handler must implement NetworkHandler trait.
use mill_net::tcp::{traits::{NetworkHandler, ConnectionId}, ServerContext};
use mill_net::errors::Result;
struct MyHandler;
impl NetworkHandler for MyHandler {
fn on_data(&self, ctx: &ServerContext, conn_id: ConnectionId, data: &[u8]) -> Result<()> {
println!("Received {} bytes from {:?}", data.len(), conn_id);
ctx.send_to(conn_id, b"some response")?;
Ok(())
}
}Re-exports§
pub use config::TcpServerConfig;pub use traits::*;
Modules§
Structs§
- Server
Context - Context for network handlers to interact with the server.
- TcpClient
- High-level TCP client
- TcpServer
- High-level TCP server