Here's a Tokio-based TCP server that can handle multiple connections simultaneously:
use tokio::io::{AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::{TcpListener, TcpStream};
use tokio::sync::Mutex;
use std::collections::HashMap;
use std::sync::Arc;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Shared state to track connections
let connections: Arc<Mutex<HashMap<usize, tokio::sync::mpsc::Sender<Vec<u8>>>>> =
Arc::new(Mutex::new(HashMap::new()));
let listener = TcpListener::bind("127.0.0.1:8080").await?;
println!("Server listening on localhost:8080");
let mut connection_counter: usize = 0;
loop {
let (socket, addr) = listener.accept().await?;
println!("New connection from: {}", addr);
// Clone the connections Arc for the connection handler
let connections_clone = Arc::clone(&connections);
// Unique ID for this connection
let conn_id = connection_counter;
connection_counter += 1;
// Spawn a task to handle this connection
tokio::spawn(async move {
handle_connection(socket, conn_id, connections_clone).await
});
}
}
async fn handle_connection(
mut socket: TcpStream,
conn_id: usize,
connections: Arc<Mutex<HashMap<usize, tokio::sync::mpsc::Sender<Vec<u8>>>>>
) -> Result<(), Box<dyn std::error::Error>> {
// Create a channel for this connection
let (tx, mut rx) = tokio::sync::mpsc::channel(100);
// Register the connection
{
let mut conns = connections.lock().await;
conns.insert(conn_id, tx);
}
// Split the socket for reading and writing
let (reader, mut writer) = socket.split();
let mut reader = BufReader::new(reader);
// Broadcast buffer
let mut buf = Vec::new();
buf.resize(1024, 0);
// Concurrent read and channel receive
loop {
tokio::select! {
// Read from socket
result = reader.read(&mut buf) => {
match result {
Ok(0) => {
println!("Connection {} closed", conn_id);
break;
}
Ok(n) => {
let message = buf[0..n].to_vec();
println!("Received from {}: {}",
conn_id,
String::from_utf8_lossy(&message)
);
// Broadcast to all connections
broadcast_message(&connections, conn_id, &message).await;
}
Err(e) => {
eprintln!("Error reading from connection {}: {}", conn_id, e);
break;
}
}
}
}
}
// Cleanup: remove this connection
{
let mut conns = connections.lock().await;
conns.remove(&conn_id);
}
Ok(())
}
async fn broadcast_message(
connections: &Arc<Mutex<HashMap<usize, tokio::sync::mpsc::Sender<Vec<u8>>>>>,
sender_id: usize,
message: &[u8]
) {
let mut conns = connections.lock().await;
// Broadcast to all connections except the sender
for (id, tx) in conns.iter_mut() {
if *id != sender_id {
let _ = tx.send(message.to_vec()).await;
}
}
}
This implementation has several key features:
-
Concurrent Connection Handling:
- Uses
tokio::spawn to create a separate task for each incoming connection
- Each connection runs independently in its own async task
-
Connection Tracking:
- Uses an
Arc<Mutex<HashMap>> to safely track active connections
- Each connection gets a unique ID
- Provides a mechanism for broadcasting messages between connections
-
Broadcast Functionality:
broadcast_message function allows sending messages to all other connected clients
- Uses a channel-based approach for inter-connection communication
-
Robust Error Handling:
- Gracefully handles connection closures
- Removes connections from the tracking map when they close
-
Non-Blocking Design:
- Uses
tokio::select! for concurrent reading
- Utilizes Tokio's async primitives for efficient I/O
To test this server, you can use multiple netcat or telnet sessions:
# In different terminal windows
nc localhost 8080
When you type in one session, the message will be broadcast to all other connected clients.
Potential Improvements:
- Add authentication
- Implement more sophisticated message routing
- Add logging
- Handle connection limits
Performance Considerations:
- The current implementation uses a mutex, which could become a bottleneck with many connections
- For high-performance scenarios, you might want to use a lock-free data structure or a more sophisticated connection management approach
Error Handling Note:
The let _ = tx.send(message.to_vec()).await; silently ignores send errors. In a production system, you'd want more robust error handling.
Would you like me to elaborate on any part of the implementation?