A high-performance WebSocket server implemented in Rust that supports topic-based pub/sub messaging with password protection and heartbeat monitoring.
- Topic-based publish/subscribe messaging
- Password-protected topics
- Automatic client heartbeat monitoring (30s timeout)
- JSON message format
- Status codes for operation results (200, 401, 403, 404, etc.)
- System commands via
/system
topic
- Install Rust if you haven't already:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
- Clone the repository:
git clone https://github.com/jrivers-iclass/rust-ws.git
cd rust-ws
- Build and run:
cargo run
The server will start on ws://localhost:8000/ws
- Make sure you have Docker and Docker Compose installed
- Run the following command:
docker-compose up -d
This will start both the WebSocket server and the client application.
- WebSocket Server:
ws://localhost:8000/ws
- Client Application:
http://localhost:80
If you prefer to run the containers separately:
# Build the image
docker build -t rust-ws-server .
# Run the container
docker run -d -p 8000:8000 rust-ws-server
# Build the image
cd client
docker build -t rust-ws-client .
# Run the container
docker run -d -p 80:80 rust-ws-client
All messages use the following JSON format:
{
"action": "subscribe|publish|create",
"topic": "topic-name",
"message": "your message here",
"password": "optional-password"
}
Creates a new topic, optionally password-protected.
{
"action": "create",
"topic": "private-room",
"message": "",
"password": "optional-password"
}
Response:
- 200: Topic created successfully
- 409: Topic already exists
Join a topic to receive messages.
{
"action": "subscribe",
"topic": "private-room",
"message": "",
"password": "required-if-protected"
}
Response:
- 200: Subscribed to topic successfully
- 401: Incorrect password
- 404: Topic does not exist
Send a message to all subscribers of a topic.
{
"action": "publish",
"topic": "private-room",
"message": "Hello everyone!",
"password": null
}
Response:
- 200: Message sent successfully
- 403: Not subscribed to topic
- 404: Topic does not exist
Send these messages to the "system" topic:
{
"action": "publish",
"topic": "system",
"message": "/command",
"password": null
}
Available commands:
/help
- Show available commands/verbose
- Toggle verbose logging
const ws = new WebSocket('ws://localhost:8000/ws');
ws.onopen = () => {
// Subscribe to a topic
ws.send(JSON.stringify({
action: "subscribe",
topic: "chat",
message: "",
password: null
}));
};
ws.onmessage = (event) => {
const response = JSON.parse(event.data);
console.log('Received:', response);
};
// Publish a message
function sendMessage(message) {
ws.send(JSON.stringify({
action: "publish",
topic: "chat",
message: message,
password: null
}));
}
- 200: Success
- 400: Bad Request (unknown action)
- 401: Unauthorized (wrong password)
- 403: Forbidden (not subscribed)
- 404: Not Found (topic doesn't exist)
- 409: Conflict (topic already exists)
- 500: Server Error