Struct WebSocket

Source
pub struct WebSocket { /* private fields */ }
Expand description

Manages the WebSocket connection; used to connect, send data, and receive data.

Connect with WebSocket::connect():

let mut ws = WebSocket::connect("wss://echo.websocket.org/").await?;

Cuustomize the handshake using a WebSocketBuilder obtained from WebSocket::builder():

let mut ws = WebSocket::builder()
    .add_subprotocol("wamp")
    .connect("wss://echo.websocket.org")
    .await?;

Use the WebSocket::send* methods to send frames:

ws.send_text("foo".to_string()).await?;

Use WebSocket::receive() to receive frames:

if let Frame::Text { payload: received_msg, .. } =  ws.receive().await? {
    // echo.websocket.org echoes text frames
    assert_eq!(received_msg, "foo".to_string());
}

Close the connection with WebSocket::close():

ws.close(Some((1000, String::new()))).await?;
if let Frame::Close{ payload: Some((status_code, _reason)) } = ws.receive().await? {
    assert_eq!(status_code, 1000);
}

§Splitting

To facilitate simulataneous reads and writes, the WebSocket can be split into a read half and a write half. The read half allows frames to be received, while the write half allows frames to be sent.

If the read half receives a Ping or Close frame, it needs to send a Pong or echo the Close frame and close the WebSocket, respectively. The write half is notified of these events, but it cannot act on them unless it is flushed. Events can be explicitly flushed, but sending a frame will also flush events. If frames are not being sent frequently, consider explicitly flushing events.

Flushing is done automatically if you are using the the WebSocket type by itself.

Implementations§

Source§

impl WebSocket

Source

pub fn builder() -> WebSocketBuilder

Constructs a WebSocketBuilder, which can be used to customize the WebSocket handshake.

Source

pub async fn connect(url: &str) -> Result<Self, WebSocketError>

Connects to a URL (and performs the WebSocket handshake).

Source

pub async fn receive(&mut self) -> Result<Frame, WebSocketError>

Receives a Frame over the WebSocket connection.

If the received frame is a Ping frame, a Pong frame will be sent. If the received frame is a Close frame, an echoed Close frame will be sent and the WebSocket will close.

Source

pub async fn receive_without_handling( &mut self, ) -> Result<Frame, WebSocketError>

Receives a Frame over the WebSocket connection without handling incoming frames. For example, receiving a Ping frame will not queue a Pong frame to be sent, and receiving a Close frame will not queue a Close frame to be sent nor close the connection.

To automatically handle incoming frames, use the receive() method instead.

Source

pub async fn send(&mut self, frame: Frame) -> Result<(), WebSocketError>

Sends an already constructed Frame over the WebSocket connection.

Source

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

Sends a Text frame over the WebSocket connection, constructed from passed arguments. continuation will be false and fin will be true. To use a custom continuation or fin, construct a Frame and use WebSocket::send().

Source

pub async fn send_binary( &mut self, payload: Vec<u8>, ) -> Result<(), WebSocketError>

Sends a Binary frame over the WebSocket connection, constructed from passed arguments. continuation will be false and fin will be true. To use a custom continuation or fin, construct a Frame and use WebSocket::send().

Source

pub async fn close( &mut self, payload: Option<(u16, String)>, ) -> Result<(), WebSocketError>

Sends a Close frame over the WebSocket connection, constructed from passed arguments, and closes the WebSocket connection. This method will attempt to wait for an echoed Close frame, which is returned.

Source

pub async fn send_ping( &mut self, payload: Option<Vec<u8>>, ) -> Result<(), WebSocketError>

Sends a Ping frame over the WebSocket connection, constructed from passed arguments.

Source

pub async fn send_pong( &mut self, payload: Option<Vec<u8>>, ) -> Result<(), WebSocketError>

Sends a Pong frame over the WebSocket connection, constructed from passed arguments.

Source

pub async fn shutdown(&mut self) -> Result<(), WebSocketError>

Shuts down the WebSocket connection without sending a Close frame. It is recommended to use the close() method instead.

Source

pub fn split(self) -> (WebSocketReadHalf, WebSocketWriteHalf)

Splits the WebSocket into a read half and a write half, which can be used separately. Accepted subprotocol and handshake response headers data will be lost.

Source

pub fn join( read_half: WebSocketReadHalf, write_half: WebSocketWriteHalf, ) -> Self

Joins together a split read half and write half to reconstruct a WebSocket.

Source

pub fn accepted_subprotocol(&self) -> &Option<String>

Returns the subprotocol that was accepted by the server during the handshake, if any. This data will be lost if the WebSocket is split.

Source

pub fn handshake_response_headers(&self) -> &Option<Vec<(String, String)>>

Returns the headers that were returned by the server during the handshake. This data will be lost if the WebSocket is split.

Trait Implementations§

Source§

impl Debug for WebSocket

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

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, 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<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> MaybeSendSync for T