A minimal WebSocket server that echoes back every message it receives, plus three clients: a browser page, a Rust program, and a Python script.
The same frame handlers serve plain ws:// and encrypted wss://
connections. Only the connection setup changes; see
Secure WebSocket below.
cd websockets/basic
cargo run --bin websocket-serverThe server listens on 127.0.0.1:8080.
Browser: open http://localhost:8080/index.html.
Rust: in another terminal:
cd websockets/basic
cargo run --bin websocket-clientType a line and press Enter to see it echoed back.
Python: requires aiohttp:
pip install aiohttp # or: pip3 install aiohttp
python websocket-client.py # or: python3 websocket-client.pyFirst create the local certificates from the repository root:
sh tls/generate-certs.shThen, from websockets/basic, start the server and client in separate
terminals:
cargo run --features tls --bin websocket-server -- --tls
cargo run --features tls --bin websocket-client -- --tlsThe secure server listens on 127.0.0.1:8443. As before, type a line in the
client terminal to get an echo. The tls feature enables OpenSSL.
Three details in the client are worth noticing:
- It installs a TLS connector explicitly.
WsClientuses plain TCP by default, so changing the URL towss://alone does not enable TLS. - It verifies the server. It trusts
../../tls/certs/ca.pemand checks the hostname, so no verification is turned off. - It offers only
http/1.1through ALPN. The WebSocket handshake is an HTTP/1.1 upgrade.
Both client branches call seal() to hide the connection's filter type. That
lets the plain and TLS connections share one message loop. On the server side,
the only difference is bind versus bind_openssl.
For other backends and client-certificate authentication, see the TLS examples.
- The guide chapter WebSocket Support covers
servers with
web::ws, heartbeats and closing, and clients. - Configuration and TLS and the TLS chapter's
WebSocket client section explain
wss://.
cargo test -p websocketThe tests exercise text echo, ping/pong, and rejection of non-GET requests through the real routes.
Run cargo test -p websocket --features tls to also build and test with TLS support enabled.