tokio-tungstenite

repository·master·Indexed 25 days ago

https://github.com/snapview/tokio-tungstenite

A Tokio binding for Tungstenite, providing asynchronous WebSocket support for the Tokio runtime. It enables non-blocking WebSocket communication via a wrapper around the tungstenite-rs library, supporting both client and server handshakes, secure connections (wss://) via native-tls or rustls, and a WebSocketStream that implements the Stream and Sink traits for message streaming.

Tokens
2.5K
Snippets
5
Records
19
Agent score
82%

What's inside tokio-tungstenite

  1. What is tokio-tungstenite?

    master
    tokio-tungstenite provides asynchronous WebSocket bindings for the Tokio stack. It is built upon the tungstenite-rs library and allows you to use WebSockets with non-blocking/asynchronous TcpStreams, enabling seamless integration with other crates in the Tokio ecosystem.
  2. Enable TLS support for secure WebSockets (wss://)

    master

    By default, TLS is not enabled. To support secure WebSockets (wss://), you must enable one of the following feature flags in your Cargo.toml:

    • native-tls: Uses native-tls for TLS support on all platforms.
    • rustls-tls-native-roots: Uses rustls with native certificate roots.
    • rustls-tls-webpki-roots: Uses rustls with webpki-roots.

    Note: If you are using rustls features with tokio-tungstenite version 0.23.0 or higher, be aware of a potential panic issue documented in the repository issues.

  3. Use WebSocketStream for message streaming

    master

    A WebSocketStream<S> is a wrapper around an underlying stream S that implements the WebSocket protocol. It implements the Stream and Sink traits from the futures crate, allowing you to treat the WebSocket as a stream of Message objects.

    Key Characteristics:

    • Reading: Reading is cancel-safe. If a next() future is dropped (e.g., in a tokio::select!), no message is lost.
    • Writing: The Sink implementation allows sending Message objects. Note that cancel-safety for the Sink side is not documented.
    • Closing: You can gracefully close the connection using the .close(msg) method.
  4. Use MaybeTlsStream to handle both plain and encrypted streams

    master

    The MaybeTlsStream<S> enum is a convenience wrapper that allows you to switch between plain TCP and TLS-encrypted streams at runtime. It abstracts away the specific TLS implementation, making it compatible with any stream that implements the standard AsyncRead and AsyncWrite traits.

    Depending on the enabled features, MaybeTlsStream can wrap:

    • MaybeTlsStream::Plain(S): An unencrypted socket stream.
    • MaybeTlsStream::NativeTls(tokio_native_tls::TlsStream<S>): An encrypted stream using native-tls (requires native-tls feature).
    • MaybeTlsStream::Rustls(tokio_rustls::client::TlsStream<S>): An encrypted stream using rustls (requires __rustls-tls feature).

    Because it implements AsyncRead and AsyncWrite, you can use it polymorphically in your code without worrying about whether the underlying connection is encrypted.

  5. Connect with custom configuration using `connect_async_with_config`

    master

    Use connect_async_with_config when you need to specify a WebSocketConfig or control the Nagle's algorithm.

    • config: An Option<WebSocketConfig> to customize the WebSocket protocol behavior.
    • disable_nagle: A bool that specifies if Nagle's algorithm should be disabled (equivalent to calling set_nodelay(true) on the underlying TCP stream). If you are unsure, leave this as false.
  6. Establish a secure WebSocket connection with client_async_tls

    master

    Use client_async_tls to perform a WebSocket handshake and automatically upgrade the underlying stream to TLS if the requested URI uses a secure scheme (e.g., wss://).

    This function is a convenience wrapper around client_async_tls_with_config that uses default settings and no specific connector.

    // R: IntoClientRequest, S: AsyncRead + AsyncWrite
    pub async fn client_async_tls<R, S>(
        request: R,
        stream: S,
    ) -> Result<(WebSocketStream<MaybeTlsStream<S>>, Response), Error>
  7. Establish a WebSocket connection with custom configuration and connector

    master

    Use client_async_tls_with_config when you need fine-grained control over the WebSocket handshake and the TLS layer. This allows you to provide:

    1. config: An optional WebSocketConfig to control protocol settings (like frame size).
    2. connector: An optional Connector to specify whether to use native-tls, rustls, or Plain connections.

    If connector is None, the library will attempt to use the best available TLS implementation based on enabled features (native-tls or __rustls-tls).

    pub async fn client_async_tls_with_config<R, S>(
        request: R,
        stream: S,
        config: Option<WebSocketConfig>,
        connector: Option<Connector>,
    ) -> Result<(WebSocketStream<MaybeTlsStream<S>>, Response), Error>
  8. Perform a WebSocket client handshake

    master

    Use client_handshake to initiate a WebSocket connection as a client. This function performs the necessary handshake negotiation and returns both the established WebSocketStream and the HTTP Response received from the server.

    Note: This function requires the handshake feature to be enabled.

  9. Convert a raw socket to a WebSocketStream without a handshake

    master

    If you have already performed a handshake or are dealing with partially read data, you can bypass the standard handshake process using:

    • WebSocketStream::from_raw_socket(stream, role, config): Creates a stream from a raw socket.
    • WebSocketStream::from_partially_read(stream, part, role, config): Creates a stream from a raw socket and a buffer containing the partially read handshake data.
  10. Connect with TLS and custom configuration using `connect_async_tls_with_config`

    master

    When the native-tls or __rustls-tls features are enabled, use connect_async_tls_with_config to establish a secure WebSocket connection with custom configuration and a specific TLS connector.

    • request: The target URL or request object.
    • config: An Option<WebSocketConfig>.
    • disable_nagle: A bool to enable/disable Nagle's algorithm (set_nodelay).
    • connector: An Option<Connector> to provide a custom TLS connector.
  11. Perform a WebSocket server handshake

    master

    Use server_handshake to accept an incoming WebSocket connection as a server. It requires a Callback (to handle the handshake logic/headers) and a closure that processes the stream. Upon success, it returns a WebSocketStream.

    Note: This function requires the handshake feature to be enabled.