Skip to main content

WebSocket

Struct WebSocket 

Source
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

  1. Created by the server after detecting an upgrade request
  2. Handler calls accept() to complete the handshake
  3. Handler sends/receives messages
  4. 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

Source

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.

Source

pub fn with_config( stream: TcpStream, client_key: String, config: WebSocketConfig, ) -> Self

Create a new WebSocket with custom configuration.

Source

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.

Source

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.

Source

pub async fn send_text(&mut self, text: &str) -> Result<(), WebSocketError>

Send a text message.

Source

pub async fn send_bytes(&mut self, data: &[u8]) -> Result<(), WebSocketError>

Send a binary message.

Source

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.

Source

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.

Source

pub async fn ping(&mut self, data: &[u8]) -> Result<(), WebSocketError>

Send a ping frame with optional payload.

Source

pub async fn pong(&mut self, data: &[u8]) -> Result<(), WebSocketError>

Send a pong frame with optional payload.

Source

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.

Source

pub fn is_open(&self) -> bool

Returns true if the connection is open and can send/receive messages.

Source

pub fn state(&self) -> &'static str

Returns the current connection state.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, _span: NoopSpan) -> Self

Instruments this future with a span (no-op when disabled).
Source§

fn in_current_span(self) -> Self

Instruments this future with the current span (no-op when disabled).
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ResponseProduces<T> for T