Struct ratchet_core::WebSocket

source ·
pub struct WebSocket<S, E> { /* private fields */ }
Expand description

An upgraded WebSocket stream.

This is created after a connection has been upgraded to speak the WebSocket protocol by using the accept, accept_with, subscribe and subscribe_with functions or by using WebSocket::from_upgraded with an already upgraded stream.

§Example


let stream = TcpStream::connect("127.0.0.1:9001").await?;
let upgraded = subscribe(WebSocketConfig::default(), stream, "ws://127.0.0.1/hello").await?;
let UpgradedClient { mut  websocket, .. } = upgraded;

let mut buf = BytesMut::new();

loop {
    match websocket.read(&mut buf).await? {
        Message::Text => {
            websocket.write(&mut buf, PayloadType::Text).await?;
            buf.clear();
        }
        Message::Binary => {
            websocket.write(&mut buf, PayloadType::Binary).await?;
            buf.clear();
        }
        Message::Ping(_) | Message::Pong(_) => {}
        Message::Close(_) => break Ok(()),
    }
}

Implementations§

source§

impl<S, E> WebSocket<S, E>

source

pub fn from_upgraded( config: WebSocketConfig, stream: S, extension: NegotiatedExtension<E>, read_buffer: BytesMut, role: Role, ) -> WebSocket<S, E>

Initialise a new WebSocket from a stream that has already executed a handshake.

§Arguments

config - The configuration to initialise the WebSocket with. stream - The stream that the handshake was executed on. extension - A negotiated extension that will be used for the session. read_buffer - The read buffer which will be used for the session. This may contain any unread data received after performing the handshake that was not required. role - The role that this WebSocket will take.

source

pub fn role(&self) -> Role

Returns the role of this WebSocket.

source

pub async fn read( &mut self, read_buffer: &mut BytesMut, ) -> Result<Message, Error>

Attempt to read some data from the WebSocket. Returning either the type of the message received or the error that was produced.

§Errors

In the event that an error is produced, an attempt is made to cleanly close the connection by sending a close frame to the peer. If this attempt fails, then the connection is abruptly closed and the cause of the error is returned.

In the event that an error is produced the contents of read_buffer must be considered to be dirty; unless the error indicates a clean closure.

§Control frames

Ratchet transparently handles ping messages received from the peer in read operations by returning a pong frame and this function will return Message::Pong if one has been received. As per RFC6455 these may be interleaved between data frames. In the event of one being received while reading a continuation, this function will then yield Message::Ping and the read_buffer will contain the data received up to that point. The callee must ensure that the contents of read_buffer are not then modified before calling read again.

§Cancel safety

This function is not cancellation safe. If the future is dropped before it has completed then both buf and the connection state are undefined. It may not be possible to recover the connection due the read operation partially completing and the state has been lost.

source

pub async fn write_text<I>(&mut self, data: I) -> Result<(), Error>
where I: AsRef<str>,

Sends a new text WebSocket message with a payload of data.

§Cancel safety

This function is not cancellation safe. If the future is dropped before it has completed then the connection state is undefined. It may not be possible to recover the connection due the write operation having written only part of the frame and the state of the write operation has been lost.

source

pub async fn write_binary<I>(&mut self, data: I) -> Result<(), Error>
where I: AsRef<[u8]>,

Sends a new binary WebSocket message with a payload of data.

§Cancel safety

This function is not cancellation safe. If the future is dropped before it has completed then the connection state is undefined. It may not be possible to recover the connection due the write operation having written only part of the frame and the state of the write operation has been lost.

source

pub async fn write_ping<I>(&mut self, data: I) -> Result<(), Error>
where I: AsRef<[u8]>,

Sends a new ping WebSocket message with a payload of data.

§Cancel safety

This function is not cancellation safe. If the future is dropped before it has completed then the connection state is undefined. It may not be possible to recover the connection due the write operation having written only part of the control frame and the state of the write operation has been lost.

source

pub async fn write_pong<I>(&mut self, data: I) -> Result<(), Error>
where I: AsRef<[u8]>,

Sends a new pong WebSocket message with a payload of data.

§Cancel safety

This function is not cancellation safe. If the future is dropped before it has completed then the connection state is undefined. It may not be possible to recover the connection due the write operation having written only part of the control frame and the state of the write operation has been lost.

source

pub async fn write<A>( &mut self, buf: A, message_type: PayloadType, ) -> Result<(), Error>
where A: AsRef<[u8]>,

Sends a new WebSocket message of message_type and with a payload of buf.

§Cancel safety

This function is not cancellation safe. If the future is dropped before it has completed then both buf and the connection state are undefined. It may not be possible to recover the connection due the read operation partially completing and the state has been lost.

source

pub async fn close(&mut self, reason: CloseReason) -> Result<(), Error>

Close this WebSocket with the reason provided.

If the WebSocket is already closed then Ok(()) is returned.

§Cancel safety

This function is not cancellation safe. If the future is dropped before it has completed then the connection state is undefined. It may not be possible to recover the connection due the write operation having written only part of the close frame and the state of the write operation has been lost.

source

pub async fn write_fragmented<A>( &mut self, buf: A, message_type: MessageType, fragment_size: usize, ) -> Result<(), Error>
where A: AsRef<[u8]>,

Constructs a new WebSocket message of message_type and with a payload of buf and chunked by fragment_size. If the length of the buffer is less than the chunk size then only a single message is sent.

§Cancel safety

This function is not cancellation safe. If the future is dropped before it has completed then the connection state is undefined. It may not be possible to recover the connection due the write operation having written only part of the buffer and the state of the write operation has been lost.

source

pub async fn flush(&mut self) -> Result<(), Error>

Flushes the WebSocket’s output stream, ensuring that all intermediately buffered contents reach their destination.

§Errors

It is considered an error if not all bytes could be written due to I/O errors or EOF being reached.

source

pub fn is_closed(&self) -> bool

Returns whether this WebSocket is closed.

source

pub fn is_active(&self) -> bool

Returns whether this WebSocket is closing or closed.

Trait Implementations§

source§

impl<S: Debug, E: Debug> Debug for WebSocket<S, E>

source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<S, E> Freeze for WebSocket<S, E>
where S: Freeze, E: Freeze,

§

impl<S, E> RefUnwindSafe for WebSocket<S, E>

§

impl<S, E> Send for WebSocket<S, E>
where S: Send, E: Send,

§

impl<S, E> Sync for WebSocket<S, E>
where S: Sync, E: Sync,

§

impl<S, E> Unpin for WebSocket<S, E>
where S: Unpin, E: Unpin,

§

impl<S, E> UnwindSafe for WebSocket<S, E>
where S: UnwindSafe, E: UnwindSafe,

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> IntoEither for T

source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
source§

impl<T> Same for T

§

type Output = T

Should always be Self
source§

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

§

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>,

§

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