pub struct WebSocket { /* private fields */ }Expand description
A WebSocket connection.
Wraps a TcpStream that has been upgraded from HTTP. Provides a
high-level API matching FastAPI/Starlette semantics.
§Lifecycle
- Created by the server after detecting an upgrade request
- Handler calls
accept()to complete the handshake - Handler sends/receives messages
- Handler calls
close()or the peer closes
§Example
async fn chat(mut ws: WebSocket) {
ws.accept(None).await.unwrap();
while let Ok(msg) = ws.receive().await {
match msg {
Message::Text(text) => {
ws.send_text(&format!("echo: {text}")).await.unwrap();
}
Message::Binary(_data) => {}
// receive() auto-replies to ping and does not surface pong.
Message::Ping(_) | Message::Pong(_) => unreachable!(),
Message::Close(_, _) => break,
}
}
ws.close(CloseCode::Normal, None).await.ok();
}Implementations§
Source§impl WebSocket
impl WebSocket
Sourcepub fn new(stream: TcpStream, client_key: String) -> Self
pub fn new(stream: TcpStream, client_key: String) -> Self
Create a new WebSocket from an upgraded TCP stream.
The client_key is the Sec-WebSocket-Key header value from the
upgrade request.
Sourcepub fn with_config(
stream: TcpStream,
client_key: String,
config: WebSocketConfig,
) -> Self
pub fn with_config( stream: TcpStream, client_key: String, config: WebSocketConfig, ) -> Self
Create a new WebSocket with custom configuration.
Sourcepub async fn accept(
&mut self,
subprotocol: Option<&str>,
) -> Result<(), WebSocketError>
pub async fn accept( &mut self, subprotocol: Option<&str>, ) -> Result<(), WebSocketError>
Complete the WebSocket handshake by sending the 101 response.
Optionally specify a subprotocol to include in the response.
§Errors
Returns an error if the handshake has already been completed or if writing the response fails.
Sourcepub async fn receive(&mut self) -> Result<Message, WebSocketError>
pub async fn receive(&mut self) -> Result<Message, WebSocketError>
Receive the next message from the client.
Automatically responds to ping frames with pong. Returns text, binary, and close messages to the caller.
§Errors
Returns an error if the connection is closed or a protocol violation occurs.
Sourcepub async fn send_text(&mut self, text: &str) -> Result<(), WebSocketError>
pub async fn send_text(&mut self, text: &str) -> Result<(), WebSocketError>
Send a text message.
Sourcepub async fn send_bytes(&mut self, data: &[u8]) -> Result<(), WebSocketError>
pub async fn send_bytes(&mut self, data: &[u8]) -> Result<(), WebSocketError>
Send a binary message.
Sourcepub async fn receive_text(&mut self) -> Result<String, WebSocketError>
pub async fn receive_text(&mut self) -> Result<String, WebSocketError>
Receive a text message.
Skips pong messages, auto-responds to pings. Returns an error if a binary or close message is received.
Sourcepub async fn receive_bytes(&mut self) -> Result<Vec<u8>, WebSocketError>
pub async fn receive_bytes(&mut self) -> Result<Vec<u8>, WebSocketError>
Receive a binary message.
Skips pong messages, auto-responds to pings. Returns an error if a text or close message is received.
Sourcepub async fn ping(&mut self, data: &[u8]) -> Result<(), WebSocketError>
pub async fn ping(&mut self, data: &[u8]) -> Result<(), WebSocketError>
Send a ping frame with optional payload.
Sourcepub async fn pong(&mut self, data: &[u8]) -> Result<(), WebSocketError>
pub async fn pong(&mut self, data: &[u8]) -> Result<(), WebSocketError>
Send a pong frame with optional payload.
Sourcepub async fn close(
&mut self,
code: CloseCode,
reason: Option<&str>,
) -> Result<(), WebSocketError>
pub async fn close( &mut self, code: CloseCode, reason: Option<&str>, ) -> Result<(), WebSocketError>
Initiate a close handshake.
Sends a close frame and transitions to CloseSent. The peer should
respond with its own close frame.