2018-04-13 03:18:42 +02:00
|
|
|
# Websocket chat example
|
|
|
|
|
2022-12-11 12:30:31 +01:00
|
|
|
This is a multi-threaded chat server example.
|
2018-04-13 03:18:42 +02:00
|
|
|
|
2022-12-11 12:30:31 +01:00
|
|
|
Fancy shiny features:
|
2018-04-13 03:18:42 +02:00
|
|
|
|
2022-12-11 12:30:31 +01:00
|
|
|
- Browser-based WebSocket client served from static html+js
|
2022-03-06 01:43:10 +01:00
|
|
|
- Chat server runs in separate thread
|
|
|
|
- Tcp listener runs in separate thread
|
|
|
|
- Application state is shared with the websocket server and a resource at `/count/`
|
2022-12-11 12:30:31 +01:00
|
|
|
- Uses actors for improved readability of code in the server.rs implementation
|
2018-04-13 03:18:42 +02:00
|
|
|
|
|
|
|
## Server
|
|
|
|
|
2020-11-30 13:41:33 +01:00
|
|
|
1. Chat server listens for incoming tcp connections. Server can access several types of message:
|
2018-04-13 03:18:42 +02:00
|
|
|
|
2022-03-06 01:43:10 +01:00
|
|
|
- `/list` - list all available rooms
|
|
|
|
- `/join name` - join room, if room does not exist, create new one
|
|
|
|
- `/name name` - set session name
|
|
|
|
- `some message` - just string, send message to all peers in same room
|
2022-12-11 12:30:31 +01:00
|
|
|
- client has to respond to heartbeat `Ping` messages, if server does not receive a heartbeat 'Pong' message for 10 seconds connection gets dropped
|
2018-04-13 03:18:42 +02:00
|
|
|
|
2022-03-06 01:43:10 +01:00
|
|
|
2. [http://localhost:8080/count/](http://localhost:8080/count/) is a non-websocket endpoint and will affect and display state.
|
2020-11-30 13:41:33 +01:00
|
|
|
|
2024-07-20 00:35:02 +02:00
|
|
|
To start server use the following
|
|
|
|
|
|
|
|
```sh
|
|
|
|
cd websockets/chat
|
|
|
|
cargo run --bin websocket-chat-server
|
|
|
|
```
|
2018-04-13 03:18:42 +02:00
|
|
|
|
2022-12-11 12:30:31 +01:00
|
|
|
## WebSocket Browser Client
|
|
|
|
|
2024-08-07 03:04:57 +02:00
|
|
|
- Open in browser: <http://localhost:8080/>.
|
|
|
|
- Use two tabs to set up a proper conversation.
|
2022-12-11 12:30:31 +01:00
|
|
|
|
|
|
|
## Python Client using aiohttp
|
2018-04-13 03:18:42 +02:00
|
|
|
|
2024-08-07 03:04:57 +02:00
|
|
|
- Client connects to server. Reads input from stdin and sends to server.
|
|
|
|
- Create a venv environment `python3 -m venv venv`.
|
|
|
|
- Launch venv environment `source ./venv/bin/activate`.
|
|
|
|
- Fetch the needed python libraries `pip3 install -r requirements.txt`.
|
|
|
|
- Then start client as `./client.py`.
|