Expand description
§WebSockets on the web 🕸️
This crate provides WebSocket support in a JavaScript runtime environment, usually a web browser.
If available it uses the experimental WebSocketStream API, otherwise the standardized WebSocket API is used.
The WebSocketStream API provides backpressure in both transmit and receive directions. The standardized WebSocket API provides backpressure only in the transmit direction; if the receive buffer overflows, the WebSocket is closed and an error is returned.
§Sending WebSocket messages
WebSocket is a message oriented protocol, i.e. it deals with sending and receiving discrete messages rather than streams of data. A message can be either text (UTF-8 string) or binary.
WebSocket and WebSocketSender implement the Sink trait for sending messages.
A Rust String or &str
is sent as a text message and
a Vec<u8>
or &[u8]
is transmitted as a binary message.
Additionally, both types implement AsyncWrite. When using this trait, each write is sent as a binary message containg the whole buffer.
§Receiving WebSocket messages
WebSocket and WebSocketReceiver implement the Stream trait for receiving messages.
The received data type is Msg
, which can either be text or binary.
Additionally, both types implement AsyncRead. When using this trait, each received message is converted to binary format and buffered to support partial reads, i.e. a read using a buffer with a size smaller than the received message.
§Example
The following example establishes a WebSocket connection to localhost
on port 8765
.
It then sends the text message Test123
and then receiving one incoming message.
Finally, it explicitly closes the WebSocket with the reason Goodbye!
.
use websocket_web::{WebSocket, CloseCode};
use futures_util::{SinkExt, StreamExt};
// Connect to WebSocket echo server running on localhost.
let mut socket = WebSocket::connect("ws://127.0.0.1:8765").await.unwrap();
// Send WebSocket text message.
socket.send("Test123").await.unwrap();
// Receive WebSocket message.
let msg = socket.next().await.unwrap().unwrap();
assert_eq!(msg.to_string(), "Test123");
// Explicitly close WebSocket with close code and reason (optional).
socket.close_with_reason(CloseCode::NormalClosure, "Goodbye!");
Structs§
- Closed
- A future that resolves once a WebSocket has been closed.
- Closed
Reason - Reason for why a WebSocket connection is closed.
- WebSocket
- A WebSocket provided by the JavaScript runtime (usually the web browser).
- WebSocket
Builder - Builder for connecting a WebSocket.
- WebSocket
Receiver - Receiving part of a WebSocket.
- WebSocket
Sender - Sending part of a WebSocket.