A TCP chat server built in Rust using tokio for asynchronous handling and broadcast channels for message distribution. This project was created to explore Rust's async capabilities and see what the language has to offer for concurrent network programming.
This chat server handles multiple connections smoothly using tokio's async capabilities. When you send a message, it broadcasts to everyone except you. The client script automatically generates random guest names for users.
The client script is rather helpful for testing the functionality of the API - it detects your Unix package manager and can install missing dependencies like telnet and fortune-mod with your permission.
The server keeps track of active usernames to prevent duplicates, so you'll get notified if someone's already using the name you want.
Everything's built around a simple Makefile system that makes development and deployment straightforward.
To ensure that each connected client uses a unique username, I created a custom ConcurrentSet
type, which internally wraps a HashSet<String>
inside a tokio::sync::RwLock
.
This allows the server to perform concurrent, asynchronous reads and exclusive writes on the set across multiple client tasks.
When a client connects and requests a username, the server checks if it already exists in the set using a read lock.
If the name is taken, the client is notified to try another one. If the name is available, a write lock is acquired to insert the username into the set safely. This ensures thread-safe validation and registration of usernames without blocking the async runtime.
The project includes a comprehensive Makefile with the following commands:
make run # Run the project in --release mode
make client # Run the demo client script
make build # Build the project in --release mode
make test # Run all unit and integration tests
make fmt # Format the code using rustfmt
make clean # Remove the target directory
make help # Show available commands
Start the server using the Makefile:
make run
The server will start on 127.0.0.1:8080
and begin listening for connections.
The easiest way to connect is using the provided client script:
make client
This script:
- Automatically detects your Unix package manager (apt, yum, brew, pacman, etc.)
- Installs required dependencies (telnet and fortune-mod) with your permission
- Connects to
127.0.0.1:8080
via telnet - Generates a random guest name (Guest10000 through Guest99999)
- Handles the connection process seamlessly
For manual testing, you can connect directly:
telnet 127.0.0.1 8080
To test the chat functionality:
- Start the server:
make run
- Open multiple terminals
- In each terminal, run:
make client
- Start chatting! Messages from one client will appear in all other connected clients
fortune is a Unix utility that generates random quotes. I used it in my bash script for simplicity :)