### Connect to a WebSocket URL with custom headers Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/fn.connect_async.html Demonstrates how to connect to a WebSocket server using `connect_async` and add custom headers to the request. This example uses a string URL and converts it into a client request, then adds an 'api-key' header before establishing the connection. ```rust use tungstenite::http::{Method, Request}; use tokio_tungstenite::connect_async; let mut request = "wss://api.example.com".into_client_request().unwrap(); request.headers_mut().insert("api-key", "42".parse().unwrap()); let (stream, response) = connect_async(request).await.unwrap(); ``` -------------------------------- ### Get WebSocketStream Configuration Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/struct.WebSocketStream.html Returns a reference to the configuration of the tungstenite stream. ```rust pub fn get_config(&self) -> &WebSocketConfig ``` -------------------------------- ### fold Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/struct.WebSocketStream.html Executes an accumulating asynchronous computation over a stream. It starts with an initial value and applies a closure to each item, updating the accumulator. ```APIDOC ## fn fold(self, init: T, f: F) -> Fold ### Description Execute an accumulating asynchronous computation over a stream, collecting all the values into one final result. ### Type Parameters - `T`: The type of the accumulator and the final result. - `Fut`: The future returned by the closure. - `F`: The type of the asynchronous closure. ### Parameters - `init`: The initial value of the accumulator. - `f`: An asynchronous closure that takes the current accumulator value and the next stream item, returning a `Future` that resolves to the updated accumulator value. ### Returns A future that resolves to the final accumulated value. ``` -------------------------------- ### Implement Sink for WebSocketStream Source: https://docs.rs/tokio-tungstenite/0.28.0/src/tokio_tungstenite/lib.rs.html Implements the `Sink` trait for `WebSocketStream` to enable sending messages. This includes methods for checking readiness, starting to send, flushing the buffer, and closing the connection. ```rust impl Sink for WebSocketStream where T: AsyncRead + AsyncWrite + Unpin, { type Error = WsError; fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { if self.ready { Poll::Ready(Ok(())) } else { // Currently blocked so try to flush the blockage away (*self).with_context(Some((ContextWaker::Write, cx)), |s| cvt(s.flush())).map(|r| { self.ready = true; r }) } } fn start_send(mut self: Pin<&mut Self>, item: Message) -> Result<(), Self::Error> { match (*self).with_context(None, |s| s.write(item)) { Ok(()) => { self.ready = true; Ok(()) } Err(WsError::Io(err)) if err.kind() == std::io::ErrorKind::WouldBlock => { // the message was accepted and queued so not an error // but `poll_ready` will now start trying to flush the block self.ready = false; Ok(()) } Err(e) => { self.ready = true; debug!("websocket start_send error: {}", e); Err(e) } } } fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { (*self).with_context(Some((ContextWaker::Write, cx)), |s| cvt(s.flush())).map(|r| { self.ready = true; match r { // WebSocket connection has just been closed. Flushing completed, not an error. Err(WsError::ConnectionClosed) => Ok(()), other => other, } }) } fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { self.ready = true; let res = if self.closing { // After queueing it, we call `flush` to drive the close handshake to completion. (*self).with_context(Some((ContextWaker::Write, cx)), |s| s.flush()) } else { (*self).with_context(Some((ContextWaker::Write, cx)), |s| s.close(None)) }; match res { Ok(()) => Poll::Ready(Ok(())), Err(WsError::ConnectionClosed) => Poll::Ready(Ok(())), Err(WsError::Io(err)) if err.kind() == std::io::ErrorKind::WouldBlock => { trace!("WouldBlock"); self.closing = true; Poll::Pending } Err(err) => { debug!("websocket close error: {}", err); Poll::Ready(Err(err)) } } } } ``` -------------------------------- ### Future for Starting Handshake Source: https://docs.rs/tokio-tungstenite/0.28.0/src/tokio_tungstenite/handshake.rs.html A future that manages the initiation of a WebSocket handshake. It polls the provided closure, which attempts to perform the handshake, and returns either the completed result or an intermediate state for further processing. ```Rust #[cfg(feature = "handshake")] impl Future for StartedHandshakeFuture where Role: HandshakeRole, Role::InternalStream: SetWaker + Unpin, F: FnOnce(AllowStd) -> Result> + Unpin, S: Unpin, AllowStd: Read + Write, { type Output = Result, Error>; fn poll(mut self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll { let inner = self.0.take().expect("future polled after completion"); trace!("Setting ctx when starting handshake"); let stream = AllowStd::new(inner.stream, ctx.waker()); match (inner.f)(stream) { ``` -------------------------------- ### client_async_with_config Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/all.html Asynchronously establishes a client-side WebSocket connection with custom configuration. ```APIDOC ## client_async_with_config ### Description Asynchronously establishes a client-side WebSocket connection with custom configuration. ### Function Signature `pub async fn client_async_with_config(url: U, config: tungstenite::protocol::WebSocketConfig) -> Result<(WebSocketStream>, Response)> where U: AsRef` ``` -------------------------------- ### Get Mutable Reference to Inner Stream Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/struct.WebSocketStream.html Returns a mutable reference to the inner stream. Requires the inner stream to implement AsyncRead and AsyncWrite. ```rust pub fn get_mut(&mut self) -> &mut S where S: AsyncRead + AsyncWrite + Unpin, ``` -------------------------------- ### take Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/struct.WebSocketStream.html Creates a new stream of at most `n` items of the underlying stream. ```APIDOC ## fn take(self, n: usize) -> Take ### Description Creates a new stream of at most `n` items of the underlying stream. ### Parameters - `n`: The maximum number of items to take from the stream. ### Returns A `Take` struct representing the limited stream. ``` -------------------------------- ### accept_async_with_config Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/all.html Asynchronously accepts a WebSocket connection with custom configuration. ```APIDOC ## accept_async_with_config ### Description Asynchronously accepts a WebSocket connection with custom configuration. ### Function Signature `pub async fn accept_async_with_config(stream: S, config: Option) -> Result<(WebSocketStream, Response)> where S: AsyncRead + AsyncWrite + Unpin` ``` -------------------------------- ### Get Shared Reference to Inner Stream Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/struct.WebSocketStream.html Returns a shared reference to the inner stream. Requires the inner stream to implement AsyncRead and AsyncWrite. ```rust pub fn get_ref(&self) -> &S where S: AsyncRead + AsyncWrite + Unpin, ``` -------------------------------- ### connect_async_with_config Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/all.html Asynchronously connects to a WebSocket server with custom configuration. ```APIDOC ## connect_async_with_config ### Description Asynchronously connects to a WebSocket server with custom configuration. ### Function Signature `pub async fn connect_async_with_config(url: U, config: tungstenite::protocol::WebSocketConfig) -> Result<(WebSocketStream>, Response)> where U: AsRef` ``` -------------------------------- ### WebSocketStream Get Reference to Inner Stream Source: https://docs.rs/tokio-tungstenite/0.28.0/src/tokio_tungstenite/lib.rs.html Provides a shared reference to the underlying raw stream. Allows inspecting the stream without consuming the WebSocketStream. ```rust pub fn get_ref(&self) -> &S where S: AsyncRead + AsyncWrite + Unpin, { self.inner.get_ref().get_ref() } ``` -------------------------------- ### client_async Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/all.html Asynchronously establishes a client-side WebSocket connection to a given URL. ```APIDOC ## client_async ### Description Asynchronously establishes a client-side WebSocket connection to a given URL. ### Function Signature `pub async fn client_async(url: U) -> Result<(WebSocketStream>, Response)> where U: AsRef` ``` -------------------------------- ### WebSocketStream Get Mutable Reference to Inner Stream Source: https://docs.rs/tokio-tungstenite/0.28.0/src/tokio_tungstenite/lib.rs.html Provides a mutable reference to the underlying raw stream. Allows modifying the stream directly while it's part of the WebSocketStream. ```rust pub fn get_mut(&mut self) -> &mut S where S: AsyncRead + AsyncWrite + Unpin, { self.inner.get_mut().get_mut() } ``` -------------------------------- ### connect_async Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/all.html Asynchronously connects to a WebSocket server. ```APIDOC ## connect_async ### Description Asynchronously connects to a WebSocket server. ### Function Signature `pub async fn connect_async(url: U) -> Result<(WebSocketStream>, Response)> where U: AsRef` ``` -------------------------------- ### Accept WebSocket Connection with Configuration Source: https://docs.rs/tokio-tungstenite/0.28.0/src/tokio_tungstenite/lib.rs.html Accepts a new WebSocket connection with a custom configuration. Useful for servers that need to control handshake details. ```rust pub async fn accept_async_with_config( stream: S, config: Option, ) -> Result, WsError> where S: AsyncRead + AsyncWrite + Unpin, { accept_hdr_async_with_config(stream, NoCallback, config).await } ``` -------------------------------- ### accept_hdr_async_with_config Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/all.html Asynchronously accepts a WebSocket connection with custom headers and configuration. ```APIDOC ## accept_hdr_async_with_config ### Description Asynchronously accepts a WebSocket connection with custom headers and configuration. ### Function Signature `pub async fn accept_hdr_async_with_config(stream: S, config: tungstenite::protocol::WebSocketConfig) -> Result<(WebSocketStream, Response)> where S: AsyncRead + AsyncWrite + Unpin` ``` -------------------------------- ### connect_async Source: https://docs.rs/tokio-tungstenite/0.28.0/index.html Connects to a given URL to establish a WebSocket connection. This is a convenience function for initiating client connections. ```APIDOC ## connect_async ### Description Connect to a given URL. This is a convenience function that handles the handshake process for client connections. ### Method Not specified (assumed to be part of an async client setup) ### Endpoint Not applicable (function call) ### Parameters * **url**: The URL to connect to (e.g., "ws://echo.websocket.org/"). ### Request Example ```rust // Example usage to connect to a WebSocket server let url = "ws://echo.websocket.org/"; let (ws_stream, response) = connect_async(url).await?; ``` ### Response #### Success Response - **WebSocketStream**: A stream that implements the WebSocket protocol. - **http::Response**: The HTTP response from the handshake. ``` -------------------------------- ### connect_async_tls_with_config Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/index.html Connects to a given URL with TLS enabled, allowing for custom configurations and TLS connectors. This extends `connect_async`. ```APIDOC ## connect_async_tls_with_config ### Description The same as `connect_async()` but the one can specify a websocket configuration, and a TLS connector to use. ### Method (Implicitly a client-side connect operation) ### Endpoint (Not applicable, as this is an SDK function) ### Parameters - **url**: (URL) - The URL to connect to. - **config**: (WebSocket configuration) - Allows specifying a websocket configuration. - **connector**: (TLS Connector) - A TLS connector to use. If no connector is specified, a default one will be created. - **disable_nagle**: (boolean) - Specifies if the Nagle’s algorithm must be disabled. If you don’t know what the Nagle’s algorithm is, better leave it to `false`. ### Request Example (Not applicable, as this is an SDK function) ### Response - **MaybeTlsStream**: A stream that might be protected with TLS. ``` -------------------------------- ### accept_async_with_config Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/index.html Accepts a new WebSocket connection with the provided stream, allowing for custom WebSocket configurations. This is an extension of `accept_async`. ```APIDOC ## accept_async_with_config ### Description The same as `accept_async()` but the one can specify a websocket configuration. ### Method (Implicitly a server-side accept operation) ### Endpoint (Not applicable, as this is an SDK function) ### Parameters - **stream**: (Underlying raw stream) - Description of the stream to wrap with WebSocket protocol. - **config**: (WebSocket configuration) - Allows specifying a websocket configuration. ### Request Example (Not applicable, as this is an SDK function) ### Response - **WebSocketStream**: A wrapper around an underlying raw stream which implements the WebSocket protocol. ``` -------------------------------- ### connect_async Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/fn.connect_async.html Connect to a given URL. Accepts any request that implements `IntoClientRequest`, which is often just `&str`, but can be a variety of types such as `httparse::Request` or `tungstenite::http::Request` for more complex uses. ```APIDOC ## connect_async ### Description Connect to a given URL. Accepts any request that implements `IntoClientRequest`, which is often just `&str`, but can be a variety of types such as `httparse::Request` or `tungstenite::http::Request` for more complex uses. ### Signature ```rust pub async fn connect_async( request: R, ) -> Result<(WebSocketStream>, Response), Error> where R: IntoClientRequest + Unpin, ``` ### Example ```rust use tungstenite::http::{Method, Request}; use tokio_tungstenite::connect_async; let mut request = "wss://api.example.com".into_client_request().unwrap(); request.headers_mut().insert("api-key", "42".parse().unwrap()); let (stream, response) = connect_async(request).await.unwrap(); ``` ``` -------------------------------- ### inspect Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/struct.WebSocketStream.html Do something with each item of this stream, afterwards passing it on. ```APIDOC ## fn inspect(self, f: F) -> Inspect ### Description Performs a side effect (e.g., logging) for each item yielded by the stream, without altering the item itself. ### Parameters - `f`: A closure that takes a reference to the stream item and performs an action. ### Returns An `Inspect` struct that wraps the stream and applies the inspection closure. ``` -------------------------------- ### client_async_tls_with_config Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/all.html Asynchronously establishes a client-side TLS-secured WebSocket connection with custom configuration. ```APIDOC ## client_async_tls_with_config ### Description Asynchronously establishes a client-side TLS-secured WebSocket connection with custom configuration. ### Function Signature `pub async fn client_async_tls_with_config(url: U, config: tungstenite::protocol::WebSocketConfig) -> Result<(WebSocketStream>, Response)> where U: AsRef` ``` -------------------------------- ### boxed Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/struct.WebSocketStream.html Wrap the stream in a Box, pinning it. ```APIDOC ## fn boxed<'a>(self) -> Pin + Send + 'a>> ### Description Wrap the stream in a Box, pinning it. ### Type Parameters - `'a`: The lifetime of the stream. ### Returns A pinned `Box` containing the stream, suitable for dynamic dispatch. ``` -------------------------------- ### zip Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/struct.WebSocketStream.html An adapter for zipping two streams together. ```APIDOC ## fn zip(self, other: St) -> Zip ### Description An adapter for zipping two streams together. It yields items as tuples of corresponding elements from both streams. ### Parameters - `other`: The other stream to zip with. ### Returns A `Zip` struct representing the zipped stream. ``` -------------------------------- ### connect_async_tls_with_config Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/all.html Asynchronously connects to a TLS-secured WebSocket server with custom configuration. ```APIDOC ## connect_async_tls_with_config ### Description Asynchronously connects to a TLS-secured WebSocket server with custom configuration. ### Function Signature `pub async fn connect_async_tls_with_config(url: U, config: tungstenite::protocol::WebSocketConfig) -> Result<(WebSocketStream>, Response)> where U: AsRef` ``` -------------------------------- ### accept_async_with_config Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/fn.accept_async_with_config.html Accepts an asynchronous stream and configures a WebSocket connection with custom settings. This function is similar to `accept_async` but provides more control over the WebSocket handshake and protocol through a `WebSocketConfig`. ```APIDOC ## accept_async_with_config ### Description Accepts an asynchronous stream and configures a WebSocket connection. This function is the same as `accept_async()` but allows the user to specify a websocket configuration. ### Signature ```rust pub async fn accept_async_with_config( stream: S, config: Option, ) -> Result, Error> where S: AsyncRead + AsyncWrite + Unpin, ``` ### Parameters * `stream`: An asynchronous read and write stream that implements `AsyncRead` and `AsyncWrite`. * `config`: An optional `WebSocketConfig` to customize the WebSocket behavior. If `None`, default configurations are used. ``` -------------------------------- ### Accept WebSocket Connection with Config and Header Callback Source: https://docs.rs/tokio-tungstenite/0.28.0/src/tokio_tungstenite/lib.rs.html Accepts a new WebSocket connection with both a custom configuration and a header processing callback. Provides maximum control over the server-side handshake. ```rust pub async fn accept_hdr_async_with_config( stream: S, callback: C, config: Option, ) -> Result, WsError> where S: AsyncRead + AsyncWrite + Unpin, C: Callback + Unpin, { let f = handshake::server_handshake(stream, move |allow_std| { tungstenite::accept_hdr_with_config(allow_std, callback, config) }); f.await.map_err(|e| match e { HandshakeError::Failure(e) => e, e => WsError::Io(std::io::Error::new(std::io::ErrorKind::Other, e.to_string())), }) } ``` -------------------------------- ### connect_async Source: https://docs.rs/tokio-tungstenite/0.28.0/src/tokio_tungstenite/connect.rs.html Connects to a given URL asynchronously. It accepts any request that implements `IntoClientRequest`. This is the primary function for establishing a WebSocket connection. ```APIDOC ## connect_async ### Description Connects to a given URL asynchronously. It accepts any request that implements `IntoClientRequest`, which can be a string slice or more complex types like `tungstenite::http::Request`. ### Method `async fn connect_async(request: R) -> Result<(WebSocketStream>, Response), Error>` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None (The `request` parameter is passed by value and is of a generic type `R` that implements `IntoClientRequest`) ### Request Example ```rust use tokio_tungstenite::connect_async; use tungstenite::http::Request; let mut request = "wss://api.example.com".into_client_request().unwrap(); request.headers_mut().insert("api-key", "42".parse().unwrap()); let (stream, response) = connect_async(request).await.unwrap(); ``` ### Response #### Success Response Returns a `Result` containing a tuple of `WebSocketStream` and `Response` on success. - `WebSocketStream>`: The established WebSocket stream. - `Response`: The HTTP response from the server during the handshake. #### Response Example ```rust // On success, the result will contain: // Ok((WebSocketStream, Response)) ``` #### Error Handling Returns `Error` on failure, which can include URL errors, I/O errors, or handshake errors. ``` -------------------------------- ### accept_hdr_async_with_config Source: https://docs.rs/tokio-tungstenite/0.28.0/src/tokio_tungstenite/lib.rs.html Accepts a new WebSocket connection with a callback for header processing and a custom configuration. This function combines the capabilities of `accept_hdr_async` and `accept_async_with_config`. ```APIDOC ## accept_hdr_async_with_config ### Description Accepts a new WebSocket connection with the provided stream, a callback for header processing, and an optional WebSocket configuration. ### Method `async fn accept_hdr_async_with_config(stream: S, callback: C, config: Option) -> Result, WsError>` ### Parameters * `stream` (S): The underlying asynchronous stream (must implement `AsyncRead` and `AsyncWrite`). * `callback` (C): A callback that receives incoming request headers and can add extra headers to the reply (must implement `Callback` and `Unpin`). * `config` (Option): An optional configuration for the WebSocket connection. ### Returns A `Result` containing either a `WebSocketStream` upon successful connection or a `WsError` if the handshake fails. ``` -------------------------------- ### accept_hdr_async_with_config Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/fn.accept_hdr_async_with_config.html Accepts a new WebSocket connection with a custom configuration. This function is an extension of `accept_hdr_async`, allowing for specific WebSocket settings to be applied. ```APIDOC ## accept_hdr_async_with_config ### Description Accepts a new WebSocket connection with a custom configuration. This function is an extension of `accept_hdr_async`, allowing for specific WebSocket settings to be applied. ### Signature ```rust pub async fn accept_hdr_async_with_config( stream: S, callback: C, config: Option, ) -> Result, Error> where S: AsyncRead + AsyncWrite + Unpin, C: Callback + Unpin, ``` ### Parameters * `stream`: The underlying asynchronous stream to accept the WebSocket connection on. * `callback`: A callback function to be executed during the handshake process. * `config`: An optional `WebSocketConfig` to customize the WebSocket connection parameters. ``` -------------------------------- ### accept_hdr_async Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/all.html Asynchronously accepts a WebSocket connection with custom headers. ```APIDOC ## accept_hdr_async ### Description Asynchronously accepts a WebSocket connection with custom headers. ### Function Signature `pub async fn accept_hdr_async(stream: S) -> Result<(WebSocketStream, Response)> where S: AsyncRead + AsyncWrite + Unpin` ``` -------------------------------- ### AllowStd::new constructor Source: https://docs.rs/tokio-tungstenite/0.28.0/src/tokio_tungstenite/compat.rs.html Initializes the AllowStd wrapper, setting up waker proxies for both read and write operations. It registers the provided handshake waker as the read waker for both proxies. ```rust pub(crate) fn new(inner: S, waker: &task::Waker) -> Self { let res = Self { inner, write_waker_proxy: Default::default(), read_waker_proxy: Default::default(), }; // Register the handshake waker as read waker for both proxies, // see also the SetWaker trait. res.write_waker_proxy.read_waker.register(waker); res.read_waker_proxy.read_waker.register(waker); res } ``` -------------------------------- ### Async WebSocket Connection with Configuration Source: https://docs.rs/tokio-tungstenite/0.28.0/src/tokio_tungstenite/connect.rs.html Connects to a WebSocket server asynchronously, allowing for custom `WebSocketConfig` and disabling Nagle's algorithm. Nagle's algorithm should typically be left enabled unless there's a specific reason to disable it. ```rust use tokio_tungstenite::connect_async_with_config; use tungstenite::protocol::WebSocketConfig; let config = WebSocketConfig { max_send_queue: None, ..Default::default() }; let (stream, response) = connect_async_with_config("wss://api.example.com", Some(config), true).await.unwrap(); ``` -------------------------------- ### Establish TLS Client Connection (Rustls) Source: https://docs.rs/tokio-tungstenite/0.28.0/src/tokio_tungstenite/tls.rs.html Establishes a TLS client connection using the rustls backend. This function configures the TLS client with root certificates and initiates the connection. ```rust let config = { let mut root_store = rustls::RootCertStore::empty(); #[cfg(feature = "webpki-roots")] { root_store.add_parsable_certificates(&rustls_native_certs::load_native_certs().map(ToOwned::to_owned).unwrap()); log::debug!( ``` -------------------------------- ### client_async_with_config Function Signature Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/fn.client_async_with_config.html This snippet shows the function signature for `client_async_with_config`, highlighting its generic parameters and return type. It is used to establish a WebSocket connection with a custom configuration. ```rust pub async fn client_async_with_config<'a, R, S>( request: R, stream: S, config: Option, ) -> Result<(WebSocketStream, Response), Error> where R: IntoClientRequest + Unpin, S: AsyncRead + AsyncWrite + Unpin, ``` -------------------------------- ### boxed_local Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/struct.WebSocketStream.html Wrap the stream in a Box, pinning it. ```APIDOC ## fn boxed_local<'a>(self) -> Pin + 'a>> ### Description Wrap the stream in a Box, pinning it. This version is for streams that do not require `Send`. ### Type Parameters - `'a`: The lifetime of the stream. ### Returns A pinned `Box` containing the stream, suitable for dynamic dispatch without `Send` bound. ``` -------------------------------- ### inspect_ok Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/struct.WebSocketStream.html Do something with the success value of this stream, afterwards passing it on. ```APIDOC ## inspect_ok ### Description Do something with the success value of this stream, afterwards passing it on. ### Method Signature ```rust fn inspect_ok(self, f: F) -> InspectOk where F: FnMut(&Self::Ok), Self: Sized, ``` ``` -------------------------------- ### client_async_tls Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/all.html Asynchronously establishes a client-side TLS-secured WebSocket connection. ```APIDOC ## client_async_tls ### Description Asynchronously establishes a client-side TLS-secured WebSocket connection. ### Function Signature `pub async fn client_async_tls(url: U) -> Result<(WebSocketStream>, Response)> where U: AsRef` ``` -------------------------------- ### connect_async_with_config Function Signature Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/fn.connect_async_with_config.html This is the function signature for `connect_async_with_config`. It allows specifying a custom WebSocket configuration and disabling Nagle's algorithm. ```rust pub async fn connect_async_with_config< R >( request: R, config: Option, disable_nagle: bool, ) -> Result<(WebSocketStream>, Response), Error> where R: IntoClientRequest + Unpin, ``` -------------------------------- ### accept_async Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/all.html Asynchronously accepts a WebSocket connection from a given stream. ```APIDOC ## accept_async ### Description Asynchronously accepts a WebSocket connection from a given stream. ### Function Signature `pub async fn accept_async(stream: S) -> Result<(WebSocketStream, Response)> where S: AsyncRead + AsyncWrite + Unpin` ``` -------------------------------- ### Async WebSocket Connection Source: https://docs.rs/tokio-tungstenite/0.28.0/src/tokio_tungstenite/connect.rs.html Establishes an asynchronous WebSocket connection to a given URL. It accepts any type that implements `IntoClientRequest`. The connection can be customized with headers. ```rust use tungstenite::http::{Method, Request}; use tokio_tungstenite::connect_async; let mut request = "wss://api.example.com".into_client_request().unwrap(); request.headers_mut().insert("api-key", "42".parse().unwrap()); let (stream, response) = connect_async(request).await.unwrap(); ``` -------------------------------- ### client_async Source: https://docs.rs/tokio-tungstenite/0.28.0/index.html Creates a WebSocket handshake from a request and a stream for client-side connections. Supports various input types for the request. ```APIDOC ## client_async ### Description Creates a WebSocket handshake from a request and a stream. For convenience, the user may call this with a url string, a URL, or a `Request`. Calling with `Request` allows the user to add a WebSocket protocol or other custom headers. ### Method Not specified (assumed to be part of an async client setup) ### Endpoint Not applicable (function call) ### Parameters * **request**: Can be a URL string, a `url::Url`, or a `tungstenite::client::Request`. * **stream**: The underlying raw stream. ### Request Example ```rust // Example usage with a URL string let url = "ws://echo.websocket.org/"; let stream = ...; // Obtain a stream (e.g., from tokio::net::TcpStream::connect()) let (ws_stream, response) = client_async(url, stream).await?; // Example usage with a Request object use tungstenite::client::Request; use url::Url; let url = Url::parse("ws://echo.websocket.org/").unwrap(); let request = Request::builder() .method(http::Method::GET) .header("Sec-WebSocket-Protocol", "graphql-ws") .uri(url.as_str()) .body(None) .unwrap(); let (ws_stream, response) = client_async(request, stream).await?; ``` ### Response #### Success Response - **WebSocketStream**: A stream that implements the WebSocket protocol. - **http::Response**: The HTTP response from the handshake. ``` -------------------------------- ### connect_async_tls_with_config Signature Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/fn.connect_async_tls_with_config.html This is the function signature for `connect_async_tls_with_config`. It outlines the parameters for establishing a TLS-secured WebSocket connection with custom configurations. ```rust pub async fn connect_async_tls_with_config< R, >( request: R, config: Option, disable_nagle: bool, connector: Option, ) -> Result<(WebSocketStream>, Response), Error> where R: IntoClientRequest + Unpin, ``` -------------------------------- ### accept_hdr_async_with_config Function Signature Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/fn.accept_hdr_async_with_config.html This is the function signature for `accept_hdr_async_with_config`. It outlines the generic types, parameters, and return type, indicating its asynchronous nature and requirements for the stream and callback types. ```rust pub async fn accept_hdr_async_with_config( stream: S, callback: C, config: Option, ) -> Result, Error> where S: AsyncRead + AsyncWrite + Unpin, C: Callback + Unpin, ``` -------------------------------- ### Accept WebSocket Connection with Header Callback Source: https://docs.rs/tokio-tungstenite/0.28.0/src/tokio_tungstenite/lib.rs.html Accepts a new WebSocket connection and allows a callback for processing request headers. This enables custom header manipulation during the handshake. ```rust pub async fn accept_hdr_async(stream: S, callback: C) -> Result, WsError> where S: AsyncRead + AsyncWrite + Unpin, C: Callback + Unpin, { accept_hdr_async_with_config(stream, callback, None).await } ``` -------------------------------- ### buffered Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/struct.WebSocketStream.html An adaptor for creating a buffered list of pending futures. ```APIDOC ## fn buffered(self, n: usize) -> Buffered ### Description An adaptor for creating a buffered list of pending futures. This processes futures concurrently up to a buffer size `n`. ### Parameters - `n`: The maximum number of futures to keep pending. ### Returns A `Buffered` struct that manages the buffered futures. ``` -------------------------------- ### try_ready_chunks Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/struct.WebSocketStream.html An adaptor for chunking up successful, ready items of the stream inside a vector. ```APIDOC ## try_ready_chunks ### Description An adaptor for chunking up successful, ready items of the stream inside a vector. ### Method Signature ```rust fn try_ready_chunks(self, capacity: usize) -> TryReadyChunks where Self: Sized, ``` ``` -------------------------------- ### peekable Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/struct.WebSocketStream.html Creates a new stream which exposes a `peek` method. ```APIDOC ## fn peekable(self) -> Peekable ### Description Creates a new stream which exposes a `peek` method, allowing inspection of the next item without consuming it. ### Returns A `Peekable` struct that wraps the stream. ``` -------------------------------- ### ready_chunks Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/struct.WebSocketStream.html An adaptor for chunking up ready items of the stream inside a vector. ```APIDOC ## fn ready_chunks(self, capacity: usize) -> ReadyChunks ### Description An adaptor for chunking up items that are immediately ready from the stream into vectors of a specified capacity. ### Parameters - `capacity`: The maximum size of each chunk vector. ### Returns A `ReadyChunks` struct representing the stream of chunked vectors. ``` -------------------------------- ### Async Client WebSocket Handshake Source: https://docs.rs/tokio-tungstenite/0.28.0/src/tokio_tungstenite/lib.rs.html Initiates an asynchronous WebSocket handshake for a client. It accepts a request and an underlying stream, returning a future that resolves to a WebSocket stream and the server's response upon success. ```Rust #[cfg(feature = "handshake")] pub async fn client_async<'a, R, S>( request: R, stream: S, ) -> Result<(WebSocketStream, Response), WsError> where R: IntoClientRequest + Unpin, S: AsyncRead + AsyncWrite + Unpin, { client_async_with_config(request, stream, None).await } ``` -------------------------------- ### Chunk Ready Stream Items Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/struct.WebSocketStream.html Use `try_ready_chunks` to group successful and immediately available items from a `TryStream` into vectors of a specified capacity. ```rust fn try_ready_chunks(self, capacity: usize) -> TryReadyChunks where Self: Sized, ``` -------------------------------- ### write_all Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/enum.MaybeTlsStream.html Attempts to write an entire buffer into this writer. This method is part of the AsyncWriteExt trait. ```APIDOC ## fn write_all<'a>(&'a mut self, src: &'a [u8]) -> WriteAll<'a, Self> ### Description Attempts to write an entire buffer into this writer. ### Method `write_all` ### Parameters #### Path Parameters - `src` (&'a [u8]): The buffer to write. ``` -------------------------------- ### chain Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/struct.WebSocketStream.html Adapter for chaining two streams. ```APIDOC ## fn chain(self, other: St) -> Chain ### Description Adapter for chaining two streams. It yields all items from the first stream, then all items from the second stream. ### Parameters - `other`: The stream to chain after the current one. ### Returns A `Chain` struct representing the chained stream. ``` -------------------------------- ### into_stream Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/struct.WebSocketStream.html Wraps a `TryStream` into a type that implements `Stream`. ```APIDOC ## into_stream ### Description Wraps a `TryStream` into a type that implements `Stream`. ### Method Signature ```rust fn into_stream(self) -> IntoStream where Self: Sized, ``` ``` -------------------------------- ### accept_hdr_async Function Signature Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/fn.accept_hdr_async.html This is the function signature for `accept_hdr_async`. It takes an `AsyncRead + AsyncWrite + Unpin` stream and a `Callback + Unpin` callback, returning a `Result` containing a `WebSocketStream` or an `Error`. ```rust pub async fn accept_hdr_async( stream: S, callback: C, ) -> Result, Error> where S: AsyncRead + AsyncWrite + Unpin, C: Callback + Unpin, ``` -------------------------------- ### Async Client WebSocket Handshake with Configuration Source: https://docs.rs/tokio-tungstenite/0.28.0/src/tokio_tungstenite/lib.rs.html Performs an asynchronous WebSocket handshake with custom configuration. This function allows specifying a `WebSocketConfig` for fine-tuning the handshake process, similar to `client_async`. ```Rust #[cfg(feature = "handshake")] pub async fn client_async_with_config<'a, R, S>( request: R, stream: S, config: Option, ) -> Result<(WebSocketStream, Response), WsError> where R: IntoClientRequest + Unpin, S: AsyncRead + AsyncWrite + Unpin, { let f = handshake::client_handshake(stream, move |allow_std| { let request = request.into_client_request()?; let cli_handshake = ClientHandshake::start(allow_std, request, config)?; cli_handshake.handshake() }); f.await.map_err(|e| match e { HandshakeError::Failure(e) => e, e => WsError::Io(std::io::Error::new(std::io::ErrorKind::Other, e.to_string())), }) } ``` -------------------------------- ### Implement Write for AllowStd Source: https://docs.rs/tokio-tungstenite/0.28.0/src/tokio_tungstenite/compat.rs.html Implements the `Write` and `flush` methods for `AllowStd` where `S` is an `AsyncWrite`. This enables writing to and flushing an asynchronous stream in a synchronous manner, mapping `Poll::Pending` to `WouldBlock`. ```rust impl Write for AllowStd where S: AsyncWrite + Unpin, { fn write(&mut self, buf: &[u8]) -> std::io::Result { trace!(file!(), line!()); match self.with_context(ContextWaker::Write, |ctx, stream| { trace!(file!(), line!()); stream.poll_write(ctx, buf) }) { Poll::Ready(r) => r, Poll::Pending => Err(std::io::Error::from(std::io::ErrorKind::WouldBlock)), } } fn flush(&mut self) -> std::io::Result<()> { trace!(file!(), line!()); match self.with_context(ContextWaker::Write, |ctx, stream| { trace!(file!(), line!()); stream.poll_flush(ctx) }) { Poll::Ready(r) => r, Poll::Pending => Err(std::io::Error::from(std::io::ErrorKind::WouldBlock)), } } } ``` -------------------------------- ### buffer_unordered Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/struct.WebSocketStream.html An adaptor for creating a buffered list of pending futures (unordered). ```APIDOC ## fn buffer_unordered(self, n: usize) -> BufferUnordered ### Description An adaptor for creating a buffered list of pending futures, processing them in the order they complete (unordered). ### Parameters - `n`: The maximum number of futures to keep pending. ### Returns A `BufferUnordered` struct that manages the unordered buffered futures. ``` -------------------------------- ### map_ok Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/struct.WebSocketStream.html Wraps the current stream in a new stream which maps the success value using the provided closure. ```APIDOC ## map_ok ### Description Wraps the current stream in a new stream which maps the success value using the provided closure. ### Method Signature ```rust fn map_ok(self, f: F) -> MapOk where Self: Sized, F: FnMut(Self::Ok) -> T, ``` ``` -------------------------------- ### client_async_tls_with_config Function Signature Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/fn.client_async_tls_with_config.html This is the function signature for `client_async_tls_with_config`. It allows specifying a request, a stream, an optional WebSocket configuration, and an optional connector for TLS-enabled WebSocket connections. ```rust pub async fn client_async_tls_with_config( request: R, stream: S, config: Option, connector: Option, ) -> Result<(WebSocketStream>, Response), Error> where R: IntoClientRequest + Unpin, S: 'static + AsyncRead + AsyncWrite + Send + Unpin, MaybeTlsStream: Unpin, ``` -------------------------------- ### client_async_tls Source: https://docs.rs/tokio-tungstenite/0.28.0/index.html Creates a WebSocket handshake over a TLS-secured stream. Automatically upgrades the stream to TLS if required by the URL. ```APIDOC ## client_async_tls ### Description Creates a WebSocket handshake from a request and a stream, upgrading the stream to TLS if required. ### Method Not specified (assumed to be part of an async client setup) ### Endpoint Not applicable (function call) ### Parameters * **request**: Can be a URL string, a `url::Url`, or a `tungstenite::client::Request`. * **stream**: The underlying raw stream. ### Request Example ```rust // Example usage for a WSS connection let url = "wss://echo.websocket.org/"; let stream = ...; // Obtain a stream let (ws_stream, response) = client_async_tls(url, stream).await?; ``` ### Response #### Success Response - **WebSocketStream**: A stream that implements the WebSocket protocol. - **http::Response**: The HTTP response from the handshake. ``` -------------------------------- ### Async TLS WebSocket Connection with Configuration Source: https://docs.rs/tokio-tungstenite/0.28.0/src/tokio_tungstenite/connect.rs.html Establishes an asynchronous TLS-enabled WebSocket connection with a specified `WebSocketConfig` and a custom TLS connector. This function is available when the 'native-tls' or '__rustls-tls' features are enabled. ```rust #[cfg(any(feature = "native-tls", "__rustls-tls"))] use tokio_tungstenite::connect_async_tls_with_config; #[cfg(any(feature = "native-tls", "__rustls-tls"))] use tungstenite::protocol::WebSocketConfig; #[cfg(any(feature = "native-tls", "__rustls-tls"))] use tokio_tungstenite::Connector; let config = WebSocketConfig { max_send_queue: None, ..Default::default() }; let connector = Connector::NativeTls; let (stream, response) = connect_async_tls_with_config("wss://api.example.com", Some(config), false, Some(connector)).await.unwrap(); ``` -------------------------------- ### write_all_buf Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/enum.MaybeTlsStream.html Attempts to write an entire buffer into this writer. This method is part of the AsyncWriteExt trait. ```APIDOC ## fn write_all_buf<'a, B>(&'a mut self, src: &'a mut B) -> WriteAllBuf<'a, Self, B> ### Description Attempts to write an entire buffer into this writer. ### Method `write_all_buf` ### Parameters #### Path Parameters - `src` (&'a mut B): A mutable reference to a buffer implementing the `Buf` trait. ``` -------------------------------- ### WebSocketStream::get_config Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/struct.WebSocketStream.html Returns a reference to the configuration of the tungstenite stream. ```APIDOC ## WebSocketStream::get_config ### Description Returns a reference to the configuration of the tungstenite stream. ### Signature ```rust pub fn get_config(&self) -> &WebSocketConfig ``` ### Returns A reference to the `WebSocketConfig`. ``` -------------------------------- ### and_then Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/struct.WebSocketStream.html Chain on a computation for when a value is ready, passing the successful results to the provided closure `f`. ```APIDOC ## and_then ### Description Chain on a computation for when a value is ready, passing the successful results to the provided closure `f`. ### Method Signature ```rust fn and_then(self, f: F) -> AndThen where F: FnMut(Self::Ok) -> Fut, Fut: TryFuture, Self: Sized, ``` ``` -------------------------------- ### WebSocketStream Configuration Source: https://docs.rs/tokio-tungstenite/0.28.0/src/tokio_tungstenite/lib.rs.html Provides access to the configuration settings of the WebSocket stream. ```APIDOC ## get_config ### Description Returns a reference to the configuration of the tungstenite stream. ### Method `get_config` ### Parameters None ### Response - **WebSocketConfig**: A reference to the WebSocket configuration. ``` -------------------------------- ### Convert TryStream to Stream Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/struct.WebSocketStream.html Use `into_stream` to convert a `TryStream` into a standard `Stream`. This is useful when you need to use stream combinators that expect a `Stream`. ```rust fn into_stream(self) -> IntoStream where Self: Sized, ``` -------------------------------- ### select_next_some Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/struct.WebSocketStream.html Returns a `Future` that resolves when the next item in this stream is ready. ```APIDOC ## fn select_next_some(&mut self) -> SelectNextSome<'_, Self> ### Description Returns a `Future` that resolves when the next item in this stream is ready. This method requires the stream to be `Unpin` and `FusedStream`. ### Returns A `SelectNextSome` future that yields the next item from the stream. ``` -------------------------------- ### by_ref Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/struct.WebSocketStream.html Borrows a stream, rather than consuming it. ```APIDOC ## fn by_ref(&mut self) -> &mut Self ### Description Borrows a stream, rather than consuming it. ### Returns A mutable reference to the stream. ``` -------------------------------- ### WebSocketStream New Constructor Source: https://docs.rs/tokio-tungstenite/0.28.0/src/tokio_tungstenite/lib.rs.html Internal constructor for creating a WebSocketStream from an existing Tungstenite WebSocket instance. Used by other public methods. ```rust pub(crate) fn new(ws: WebSocket>) -> Self { Self { inner: ws, closing: false, ended: false, ready: true } } ``` -------------------------------- ### Conversion Traits Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/enum.MaybeTlsStream.html Methods related to the `From`, `Into`, `TryFrom`, and `TryInto` traits for type conversions. ```APIDOC ### impl From for T #### fn from(t: T) -> T Returns the argument unchanged. ``` ```APIDOC ### impl Into for T where U: From, #### fn into(self) -> U Calls `U::from(self)`. ``` ```APIDOC ### impl TryFrom for T where U: Into, #### type Error = Infallible The type returned in the event of a conversion error. #### fn try_from(value: U) -> Result>::Error> Performs the conversion. ``` ```APIDOC ### impl TryInto for T where U: TryFrom, #### type Error = >::Error The type returned in the event of a conversion error. #### fn try_into(self) -> Result>::Error> Performs the conversion. ``` -------------------------------- ### accept_async Source: https://docs.rs/tokio-tungstenite/0.28.0/tokio_tungstenite/fn.accept_async.html Accepts a new WebSocket connection with the provided stream. This function will internally call `server::accept` to create a handshake representation and returns a future representing the resolution of the WebSocket handshake. The returned future will resolve to either `WebSocketStream` or `Error` depending if it’s successful or not. This is typically used after a socket has been accepted from a `TcpListener`. That socket is then passed to this function to perform the server half of the accepting a client’s websocket connection. ```APIDOC ## accept_async ### Description Accepts a new WebSocket connection with the provided stream. ### Signature ```rust pub async fn accept_async(stream: S) -> Result, Error> where S: AsyncRead + AsyncWrite + Unpin, ``` ### Parameters * `stream`: An object implementing `AsyncRead`, `AsyncWrite`, and `Unpin` traits, representing the underlying network stream. ```