Struct WebSocket

pub struct WebSocket<Stream> { /* private fields */ }
Expand description

WebSocket input-output stream.

This is THE structure you want to create to be able to speak the WebSocket protocol. It may be created by calling connect, accept or client functions.

Use WebSocket::read, WebSocket::send to received and send messages.

Implementations§

§

impl<Stream> WebSocket<Stream>

pub fn from_raw_socket( stream: Stream, role: Role, config: Option<WebSocketConfig>, ) -> WebSocket<Stream>

Convert a raw socket into a WebSocket without performing a handshake.

§Panics

Panics if config is invalid e.g. max_write_buffer_size <= write_buffer_size.

pub fn from_partially_read( stream: Stream, part: Vec<u8>, role: Role, config: Option<WebSocketConfig>, ) -> WebSocket<Stream>

Convert a raw socket into a WebSocket without performing a handshake.

§Panics

Panics if config is invalid e.g. max_write_buffer_size <= write_buffer_size.

pub fn get_ref(&self) -> &Stream

Returns a shared reference to the inner stream.

pub fn get_mut(&mut self) -> &mut Stream

Returns a mutable reference to the inner stream.

pub fn set_config(&mut self, set_func: impl FnOnce(&mut WebSocketConfig))

Change the configuration.

§Panics

Panics if config is invalid e.g. max_write_buffer_size <= write_buffer_size.

pub fn get_config(&self) -> &WebSocketConfig

Read the configuration.

pub fn can_read(&self) -> bool

Check if it is possible to read messages.

Reading is impossible after receiving Message::Close. It is still possible after sending close frame since the peer still may send some data before confirming close.

pub fn can_write(&self) -> bool

Check if it is possible to write messages.

Writing gets impossible immediately after sending or receiving Message::Close.

§

impl<Stream> WebSocket<Stream>
where Stream: Read + Write,

pub fn read(&mut self) -> Result<Message, ProtocolError>

Read a message from stream, if possible.

This will also queue responses to ping and close messages. These responses will be written and flushed on the next call to read, write or flush.

§Closing the connection

When the remote endpoint decides to close the connection this will return the close message with an optional close frame.

You should continue calling read, write or flush to drive the reply to the close frame until [Error::ConnectionClosed] is returned. Once that happens it is safe to drop the underlying connection.

pub fn send(&mut self, message: Message) -> Result<(), ProtocolError>

Writes and immediately flushes a message. Equivalent to calling write then flush.

pub fn write(&mut self, message: Message) -> Result<(), ProtocolError>

Write a message to the provided stream, if possible.

A subsequent call should be made to flush to flush writes.

In the event of stream write failure the message frame will be stored in the write buffer and will try again on the next call to write or flush.

If the write buffer would exceed the configured WebSocketConfig::max_write_buffer_size Err(WriteBufferFull(msg_frame)) is returned.

This call will generally not flush. However, if there are queued automatic messages they will be written and eagerly flushed.

For example, upon receiving ping messages this crate queues pong replies automatically. The next call to read, write or flush will write & flush the pong reply. This means you should not respond to ping frames manually.

You can however send pong frames manually in order to indicate a unidirectional heartbeat as described in RFC 6455. Note that if read returns a ping, you should flush before passing a custom pong to write, otherwise the automatic queued response to the ping will not be sent as it will be replaced by your custom pong message.

§Errors
  • If the WebSocket’s write buffer is full, [Error::WriteBufferFull] will be returned along with the equivalent passed message frame.
  • If the connection is closed and should be dropped, this will return [Error::ConnectionClosed].
  • If you try again after [Error::ConnectionClosed] was returned either from here or from read, [Error::AlreadyClosed] will be returned. This indicates a program error on your part.
  • [Error::Io] is returned if the underlying connection returns an error (consider these fatal except for WouldBlock).
  • [Error::Capacity] if your message size is bigger than the configured max message size.

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

Flush writes.

Ensures all messages previously passed to write and automatic queued pong responses are written & flushed into the underlying stream.

pub fn close(&mut self, code: Option<CloseFrame>) -> Result<(), ProtocolError>

Close the connection.

This function guarantees that the close frame will be queued. There is no need to call it again. Calling this function is the same as calling write(Message::Close(..)).

After queuing the close frame you should continue calling read or flush to drive the close handshake to completion.

The websocket RFC defines that the underlying connection should be closed by the server. This crate takes care of this asymmetry for you.

When the close handshake is finished (we have both sent and received a close message), read or flush will return [Error::ConnectionClosed] if this endpoint is the server.

If this endpoint is a client, [Error::ConnectionClosed] will only be returned after the server has closed the underlying connection.

It is thus safe to drop the underlying connection as soon as [Error::ConnectionClosed] is returned from read or flush.

Trait Implementations§

§

impl<Stream> Debug for WebSocket<Stream>
where Stream: Debug,

§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<Stream> !Freeze for WebSocket<Stream>

§

impl<Stream> RefUnwindSafe for WebSocket<Stream>
where Stream: RefUnwindSafe,

§

impl<Stream> Send for WebSocket<Stream>
where Stream: Send,

§

impl<Stream> Sync for WebSocket<Stream>
where Stream: Sync,

§

impl<Stream> Unpin for WebSocket<Stream>
where Stream: Unpin,

§

impl<Stream> UnwindSafe for WebSocket<Stream>
where Stream: 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
§

impl<'a, T, E> AsTaggedExplicit<'a, E> for T
where T: 'a,

§

fn explicit(self, class: Class, tag: u32) -> TaggedParser<'a, Explicit, Self, E>

§

impl<'a, T, E> AsTaggedImplicit<'a, E> for T
where T: 'a,

§

fn implicit( self, class: Class, constructed: bool, tag: u32, ) -> TaggedParser<'a, Implicit, Self, E>

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.

§

impl<T> FutureExt for T

§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
§

impl<T> Instrument for T

§

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

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

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

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
§

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

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
§

impl<T, U> RamaInto<U> for T
where U: RamaFrom<T>,

§

fn rama_into(self) -> U

§

impl<T, U> RamaInto<U> for T
where U: RamaFrom<T>,

§

fn rama_into(self) -> U

§

impl<T, U> RamaTryInto<U> for T
where U: RamaTryFrom<T>,

§

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

§

fn rama_try_into(self) -> Result<U, <U as RamaTryFrom<T>>::Error>

§

impl<T, U> RamaTryInto<U> for T
where U: RamaTryFrom<T>,

§

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

§

fn rama_try_into(self) -> Result<U, <U as RamaTryFrom<T>>::Error>

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.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

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
§

fn with_current_subscriber(self) -> WithDispatch<Self>

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

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