### Configure and Receive Messages Source: https://docs.rs/actix-ws/0.3.0/actix_ws/struct.AggregatedMessageStream.html Examples for setting the maximum continuation size and consuming messages from the stream. ```rust // increase the allowed size from 1MB to 8MB let mut stream = stream.max_continuation_size(8 * 1024 * 1024); while let Some(Ok(msg)) = stream.recv().await { // handle message } ``` ```rust while let Some(Ok(msg)) = stream.recv().await { // handle message } ``` -------------------------------- ### WebSocket server implementation Source: https://docs.rs/actix-ws/0.3.0/actix_ws/fn.handle.html A complete example demonstrating how to handle WebSocket traffic, including ping responses and message processing within an actix-web server. ```rust use std::io; use actix_web::{middleware::Logger, web, App, HttpRequest, HttpServer, Responder}; use actix_ws::Message; use futures_util::StreamExt as _; async fn ws(req: HttpRequest, body: web::Payload) -> actix_web::Result { let (response, mut session, mut msg_stream) = actix_ws::handle(&req, body)?; actix_web::rt::spawn(async move { while let Some(Ok(msg)) = msg_stream.next().await { match msg { Message::Ping(bytes) => { if session.pong(&bytes).await.is_err() { return; } } Message::Text(msg) => println!("Got text: {msg}"), _ => break, } } let _ = session.close(None).await; }); Ok(response) } #[tokio::main(flavor = "current_thread")] async fn main() -> io::Result<()> { HttpServer::new(move || { App::new() .route("/ws", web::get().to(ws)) .wrap(Logger::default()) }) .bind(("127.0.0.1", 8080))? .run() .await } ``` -------------------------------- ### Handle WebSocket Connection in Actix Web Source: https://docs.rs/actix-ws/0.3.0/src/actix_ws/lib.rs.html This example demonstrates how to integrate actix-ws into an Actix Web application to handle WebSocket connections. It shows setting up a route, handling incoming messages (like Pings), and sending responses. Ensure the `actix-ws` and `futures-util` crates are added to your Cargo.toml. ```rust use std::io; use actix_web::{middleware::Logger, web, App, HttpRequest, HttpServer, Responder}; use actix_ws::Message; use futures_util::StreamExt as _; async fn ws(req: HttpRequest, body: web::Payload) -> actix_web::Result { let (response, mut session, mut msg_stream) = actix_ws::handle(&req, body)?; actix_web::rt::spawn(async move { while let Some(Ok(msg)) = msg_stream.next().await { match msg { Message::Ping(bytes) => { if session.pong(&bytes).await.is_err() { return; } } Message::Text(msg) => println!("Got text: {msg}"), _ => break, } } let _ = session.close(None).await; }); Ok(response) } #[tokio::main(flavor = "current_thread")] async fn main() -> io::Result<()> { HttpServer::new(move || { App::new() .route("/ws", web::get().to(ws)) .wrap(Logger::default()) }) .bind(("127.0.0.1", 8080))?; .run() .await } ``` -------------------------------- ### Send continuation frames Source: https://docs.rs/actix-ws/0.3.0/actix_ws/struct.Session.html Manually sends fragmented messages using continuation frames. Must start with First and end with Last. ```rust session.continuation(Item::FirstText("Hello".into())).await?; session.continuation(Item::Continue(b", World"[..].into())).await?; session.continuation(Item::Last(b"!"[..].into())).await?; ``` -------------------------------- ### Stream Implementation for StreamingBody Source: https://docs.rs/actix-ws/0.3.0/actix_ws/struct.StreamingBody.html Implements the `Stream` trait for `StreamingBody`, defining the `Item` type as `Result` and providing methods for polling the next item and getting the stream's size hint. ```rust type Item = Result ``` ```rust fn poll_next( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll> ``` ```rust fn size_hint(&self) -> (usize, Option) ``` -------------------------------- ### Initiate WebSocket Handshake and Session Source: https://docs.rs/actix-ws/0.3.0/src/actix_ws/lib.rs.html This function performs the WebSocket handshake and sets up the session and message stream. It returns the HTTP response, a `Session` object for managing the WebSocket connection, and a `MessageStream` for receiving messages. Requires `actix-http` and `tokio` dependencies. ```rust pub fn handle( req: &HttpRequest, body: web::Payload, ) -> Result<(HttpResponse, Session, MessageStream), actix_web::Error> { let mut response = handshake(req.head())?; let (tx, rx) = channel(32); Ok(( response .message_body(BodyStream::new(StreamingBody::new(rx)).boxed())? .into(), Session::new(tx), MessageStream::new(body.into_inner()), )) } ``` -------------------------------- ### actix_ws::handle Source: https://docs.rs/actix-ws/0.3.0/src/actix_ws/lib.rs.html Initializes a WebSocket connection by performing the handshake and returning the necessary components to manage the session and message stream. ```APIDOC ## handle(req: &HttpRequest, body: web::Payload) ### Description Begins handling WebSocket traffic by performing the handshake and returning an HTTP response, a session handle, and a message stream. ### Parameters #### Request Parameters - **req** (&HttpRequest) - Required - The incoming HTTP request. - **body** (web::Payload) - Required - The request body payload. ### Response #### Success Response (200) - **HttpResponse** - The WebSocket handshake response. - **Session** - Handle for sending messages to the client. - **MessageStream** - Stream for receiving messages from the client. ``` -------------------------------- ### Create a new WebSocket session handle Source: https://docs.rs/actix-ws/0.3.0/src/actix_ws/session.rs.html Internal constructor for the `Session` struct. It initializes the session with a sender for messages and an atomic boolean to track its closed state. ```rust pub(super) fn new(inner: Sender) -> Self { Session { inner: Some(inner), closed: Arc::new(AtomicBool::new(false)), } } ``` -------------------------------- ### Structs in actix-ws 0.3.0 Source: https://docs.rs/actix-ws/0.3.0/actix_ws/all.html Overview of the structs available in the actix-ws 0.3.0 crate. ```APIDOC ## Structs ### AggregatedMessageStream Represents an aggregated stream of messages. ### CloseReason Details about the reason for closing a connection. ### Closed Indicates that a connection has been closed. ### MessageStream Represents a stream of WebSocket messages. ### Session Represents an active WebSocket session. ### StreamingBody Represents a streaming body for messages. ``` -------------------------------- ### Implement Any for T Source: https://docs.rs/actix-ws/0.3.0/actix_ws/enum.Item.html Provides runtime type information for any type T. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### WithSubscriber Implementation Source: https://docs.rs/actix-ws/0.3.0/actix_ws/enum.ProtocolError.html Implementations for attaching subscribers to types. ```APIDOC ## impl WithSubscriber for T ### fn with_subscriber(self, subscriber: S) -> WithDispatch where S: Into, Attaches the provided `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more ### fn with_current_subscriber(self) -> WithDispatch Attaches the current default `Subscriber` to this type, returning a `WithDispatch` wrapper. Read more ``` -------------------------------- ### Implement From for T Source: https://docs.rs/actix-ws/0.3.0/actix_ws/enum.Item.html Provides a conversion from T to T, returning the argument unchanged. ```rust fn from(t: T) -> T ``` -------------------------------- ### Functions in actix-ws 0.3.0 Source: https://docs.rs/actix-ws/0.3.0/actix_ws/all.html Overview of the functions available in the actix-ws 0.3.0 crate. ```APIDOC ## Functions ### handle Handles incoming WebSocket connections and messages. This function is typically used within an Actix web service to manage WebSocket interactions. ``` -------------------------------- ### Implement PartialEq for Item Source: https://docs.rs/actix-ws/0.3.0/actix_ws/enum.Item.html Enables comparison of two Item instances for equality. ```rust fn eq(&self, other: &Item) -> bool ``` ```rust fn ne(&self, other: &Rhs) -> bool ``` -------------------------------- ### TryInto Conversion Method Source: https://docs.rs/actix-ws/0.3.0/actix_ws/struct.Session.html Performs the conversion into the target type. ```rust fn try_into(self) -> Result>::Error> ``` -------------------------------- ### VZip Implementation Source: https://docs.rs/actix-ws/0.3.0/actix_ws/enum.ProtocolError.html Implementation of VZip for types V that implement MultiLane. ```APIDOC ## impl VZip for T where V: MultiLane, ### fn vzip(self) -> V ``` -------------------------------- ### Implement Into for T Source: https://docs.rs/actix-ws/0.3.0/actix_ws/enum.Item.html Provides a conversion from T to U, leveraging the From for U implementation. ```rust fn into(self) -> U ``` -------------------------------- ### Send Continuation Message with Actix-ws Session Source: https://docs.rs/actix-ws/0.3.0/src/actix_ws/session.rs.html Use the `continuation` method to send a continuation message as part of a larger message. Ensure the session is still open before calling. ```rust pub async fn continuation(&mut self, msg: Item) -> Result<(), Closed> { self.pre_check(); if let Some(inner) = self.inner.as_mut() { inner .send(Message::Continuation(msg)) .await .map_err(|_| Closed) } else { Err(Closed) } } ``` -------------------------------- ### actix_ws::handle Source: https://docs.rs/actix-ws/0.3.0/actix_ws/fn.handle.html The handle function initiates the WebSocket handshake and returns the necessary components to manage the connection. ```APIDOC ## Function actix_ws::handle ### Description Begins handling WebSocket traffic by performing the handshake and returning the response, session, and message stream. ### Parameters - **req** (&HttpRequest) - Required - The incoming HTTP request to upgrade. - **body** (Payload) - Required - The request payload. ### Response - **Result<(HttpResponse, Session, MessageStream), Error>** - Returns a tuple containing the handshake response, the session controller, and the stream of incoming messages on success, or an Error if the handshake fails. ``` -------------------------------- ### Stream Conversion and Iteration Source: https://docs.rs/actix-ws/0.3.0/actix_ws/struct.MessageStream.html Utilities for converting streams and iterating over their elements. ```APIDOC ## fn into_stream(self) -> IntoStream ### Description Wraps a `TryStream` into a type that implements `Stream`. ### Method (Implicitly part of stream processing, no explicit HTTP method) ### Endpoint (N/A - This is a function within a stream processing library) ### Parameters (N/A) ### Request Example (N/A) ### Response #### Success Response (200) (N/A - Returns a converted stream) #### Response Example (N/A) ``` ```APIDOC ## fn try_next(&mut self) -> TryNext<'_, Self> ### Description Creates a future that attempts to resolve the next item in the stream. If an error is encountered before the next item, the error is returned instead. ### Method (Implicitly part of stream processing, no explicit HTTP method) ### Endpoint (N/A - This is a function within a stream processing library) ### Parameters #### Path Parameters (N/A) #### Query Parameters (N/A) #### Request Body (N/A) ### Request Example (N/A) ### Response #### Success Response (200) (N/A - Returns a future) #### Response Example (N/A) ``` ```APIDOC ## fn try_for_each(self, f: F) -> TryForEach ### Description Attempts to run this stream to completion, executing the provided asynchronous closure for each element on the stream. ### Method (Implicitly part of stream processing, no explicit HTTP method) ### Endpoint (N/A - This is a function within a stream processing library) ### Parameters (N/A) ### Request Example (N/A) ### Response #### Success Response (200) (N/A - Returns a future) #### Response Example (N/A) ``` -------------------------------- ### handle function Source: https://docs.rs/actix-ws/0.3.0/actix_ws The primary entry point for initiating WebSocket traffic handling within an Actix Web application. ```APIDOC ## handle ### Description Begin handling websocket traffic for an incoming request. ### Function Signature `pub fn handle(req: &HttpRequest, stream: Payload) -> Result<(HttpRequest, Payload, Session), ProtocolError>` ### Parameters - **req** (&HttpRequest) - The incoming HTTP request. - **stream** (Payload) - The request payload stream. ### Returns - **Result** - Returns a tuple containing the request, payload, and a Session handle, or a ProtocolError if the handshake fails. ``` -------------------------------- ### continuation Source: https://docs.rs/actix-ws/0.3.0/src/actix_ws/session.rs.html Sends a continuation frame to the WebSocket client. ```APIDOC ## continuation ### Description Sends a continuation frame to the WebSocket client. This is used for fragmented messages. ### Parameters - **msg** (Item) - Required - The continuation item to send. ### Response - **Result<(), Closed>** - Returns Ok(()) on success, or Closed if the session is no longer active. ``` -------------------------------- ### Implement TryInto for T Source: https://docs.rs/actix-ws/0.3.0/actix_ws/enum.Item.html Enables fallible conversion from T to U, using the TryFrom for U implementation. ```rust type Error = >::Error ``` ```rust fn try_into(self) -> Result>::Error> ``` -------------------------------- ### Configure Maximum Continuation Size Source: https://docs.rs/actix-ws/0.3.0/src/actix_ws/aggregated.rs.html Sets the maximum allowed size for aggregated continuations in bytes. The default limit is 1 MiB. ```rust # use actix_ws::AggregatedMessageStream; # async fn test(stream: AggregatedMessageStream) { // increase the allowed size from 1MB to 8MB let mut stream = stream.max_continuation_size(8 * 1024 * 1024); while let Some(Ok(msg)) = stream.recv().await { // handle message } # } ``` -------------------------------- ### Stream Adaptors Source: https://docs.rs/actix-ws/0.3.0/actix_ws/struct.MessageStream.html Methods for transforming and managing streams, such as buffering, chunking, and zipping. ```APIDOC ## Stream Adaptors ### Description Methods to manipulate, buffer, and combine streams. ### Methods - **fuse()**: Fuses a stream so poll_next is not called after completion. - **buffered(n: usize)**: Creates a buffered list of pending futures. - **buffer_unordered(n: usize)**: Creates a buffered list of pending futures (unordered). - **zip(other)**: Zips two streams together. - **chain(other)**: Chains two streams. - **chunks(capacity: usize)**: Chunks items into a vector. - **ready_chunks(capacity: usize)**: Chunks ready items into a vector. ``` -------------------------------- ### Stream Adaptors Source: https://docs.rs/actix-ws/0.3.0/actix_ws/struct.StreamingBody.html Methods for transforming and inspecting streams. ```APIDOC ## Stream Adaptors ### Description Methods to transform, chunk, or inspect items within a stream. ### Methods - **peekable()**: Creates a new stream which exposes a peek method. - **chunks(capacity: usize)**: Adaptor for chunking items into a vector. - **ready_chunks(capacity: usize)**: Adaptor for chunking ready items into a vector. - **inspect(f: F)**: Executes a closure on each item while passing it through. - **left_stream()**: Wraps stream as the left variant of an Either stream. - **right_stream()**: Wraps stream as the right variant of an Either stream. ``` -------------------------------- ### MessageStream Configuration and Usage Source: https://docs.rs/actix-ws/0.3.0/actix_ws/struct.MessageStream.html Methods for configuring the MessageStream behavior and receiving messages. ```APIDOC ## MessageStream::max_frame_size ### Description Sets the maximum permitted size for received WebSocket frames, in bytes. By default, up to 64KiB is allowed. Any received frames larger than the permitted value will return `Err(ProtocolError::Overflow)`. ### Parameters - **max_size** (usize) - Required - The maximum frame size in bytes. ### Request Example ```rust // increase permitted frame size from 64KB to 1MB let stream = stream.max_frame_size(1024 * 1024); ``` ## MessageStream::aggregate_continuations ### Description Returns a stream wrapper that collects continuation frames into their equivalent aggregated forms (binary or text). ## MessageStream::recv ### Description Waits for the next item from the message stream. This is a convenience method for calling the `Stream` implementation. ### Response - **Option>** - The next message from the stream or None if exhausted. ### Response Example ```rust while let Some(Ok(msg)) = stream.recv().await { // handle message } ``` ``` -------------------------------- ### Send pong frame Source: https://docs.rs/actix-ws/0.3.0/actix_ws/struct.Session.html Responds to a ping frame with a pong frame. ```rust match msg { Message::Ping(bytes) => { let _ = session.pong(&bytes).await; } _ => (), } ``` -------------------------------- ### Send continuation frame for WebSocket messages Source: https://docs.rs/actix-ws/0.3.0/src/actix_ws/session.rs.html Manually sends a continuation frame for a multi-frame WebSocket message. Use `Item::FirstText`, `Item::ContinueText`, `Item::LastText` for text messages, and similarly for binary. Ensure frames are sent in the correct sequence (First, Continue..., Last). Control messages can interrupt continuations. ```rust session.continuation(Item::FirstText("Hello".into())).await?; ``` -------------------------------- ### Implement Debug for Item Source: https://docs.rs/actix-ws/0.3.0/actix_ws/enum.Item.html Provides a way to format the Item enum for debugging purposes. ```rust fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> ``` -------------------------------- ### Convenience method for TryStream::try_poll_next on Unpin streams Source: https://docs.rs/actix-ws/0.3.0/actix_ws/struct.MessageStream.html This method is a convenience wrapper for calling `TryStream::try_poll_next` specifically on stream types that implement `Unpin`. It simplifies polling for results from such streams. ```rust fn try_poll_next_unpin( &mut self, cx: &mut Context<'_>, ) -> Poll>> where Self: Unpin, ``` -------------------------------- ### Implement WithSubscriber for T Source: https://docs.rs/actix-ws/0.3.0/actix_ws/enum.Item.html Allows attaching a Subscriber to a type, returning a WithDispatch wrapper. ```rust fn with_subscriber(self, subscriber: S) -> WithDispatch where S: Into ``` ```rust fn with_current_subscriber(self) -> WithDispatch ``` -------------------------------- ### Enums in actix-ws 0.3.0 Source: https://docs.rs/actix-ws/0.3.0/actix_ws/all.html Overview of the enums available in the actix-ws 0.3.0 crate. ```APIDOC ## Enums ### AggregatedMessage An enum representing different types of aggregated WebSocket messages. ### CloseCode Enumerates the possible close codes for WebSocket connections. ### Item Represents an item within a message stream. ### Message Represents a WebSocket message, which can be text, binary, ping, pong, or close. ### ProtocolError Enumerates possible protocol errors that can occur during WebSocket communication. ``` -------------------------------- ### Define Session struct Source: https://docs.rs/actix-ws/0.3.0/actix_ws/struct.Session.html The internal structure definition for the WebSocket session handle. ```rust pub struct Session { /* private fields */ } ``` -------------------------------- ### WebSocket Session Methods Source: https://docs.rs/actix-ws/0.3.0/src/actix_ws/session.rs.html Methods available on the Session handle to communicate with the WebSocket client. ```APIDOC ## Session Methods ### Description Methods to send various types of WebSocket frames to the client. ### Methods - **text(msg: impl Into)**: Sends a text message. - **binary(msg: impl Into)**: Sends raw binary data. - **ping(msg: &[u8])**: Sends a ping frame to check connection status. - **pong(msg: &[u8])**: Sends a pong frame in response to a ping. - **continuation(item: Item)**: Sends continuation frames for fragmented messages. ### Parameters - **msg** (String/Bytes/Slice) - Required - The payload to send. - **item** (Item) - Required - The continuation frame variant (FirstText, FirstBinary, Continue, Last). ### Response - **Result<(), Closed>** - Returns Ok(()) on success, or a Closed error if the session is no longer active. ``` -------------------------------- ### Implement VZip for T Source: https://docs.rs/actix-ws/0.3.0/actix_ws/enum.Item.html Provides vector zipping functionality for type T with a MultiLane V. ```rust fn vzip(self) -> V ``` -------------------------------- ### Close Session with Actix-ws Session Source: https://docs.rs/actix-ws/0.3.0/src/actix_ws/session.rs.html Call the `close` method to send a close message and terminate the session. Any subsequent use of the session or its clones will result in an error. ```rust pub async fn close(mut self, reason: Option) -> Result<(), Closed> { self.pre_check(); if let Some(inner) = self.inner.take() { self.closed.store(true, Ordering::Relaxed); inner.send(Message::Close(reason)).await.map_err(|_| Closed) } else { Err(Closed) } } ``` -------------------------------- ### MessageStream Configuration and Reception Source: https://docs.rs/actix-ws/0.3.0/src/actix_ws/stream.rs.html Methods for configuring the MessageStream behavior and receiving messages from a WebSocket connection. ```APIDOC ## MessageStream Configuration ### Description Configures the MessageStream instance to handle frame sizes and message aggregation. ### Methods - **max_frame_size(max_size: usize)**: Sets the maximum permitted size for received WebSocket frames in bytes. Defaults to 64KiB. - **aggregate_continuations()**: Returns an AggregatedMessageStream that collects continuation frames into binary or text messages. - **recv()**: Asynchronously waits for the next item from the message stream. ### Parameters - **max_size** (usize) - Required - The maximum frame size in bytes. ### Usage Example ```rust // Increase permitted frame size to 1MB let stream = stream.max_frame_size(1024 * 1024); // Receive messages in a loop while let Some(Ok(msg)) = stream.recv().await { // handle message } ``` ``` -------------------------------- ### Implement Borrow for T Source: https://docs.rs/actix-ws/0.3.0/actix_ws/enum.Item.html Allows borrowing a reference to T from T. ```rust fn borrow(&self) -> &T ``` -------------------------------- ### Stream Adapters Source: https://docs.rs/actix-ws/0.3.0/actix_ws/struct.AggregatedMessageStream.html Various adapters to modify or enhance stream behavior. ```APIDOC ## Stream Adapters ### `boxed_local` #### Description Wraps the stream in a Box, pinning it. ### `buffered` #### Description An adaptor for creating a buffered list of pending futures. ### `buffer_unordered` #### Description An adaptor for creating a buffered list of pending futures (unordered). ### `zip` #### Description An adapter for zipping two streams together. ### `chain` #### Description Adapter for chaining two streams. ### `peekable` #### Description Creates a new stream which exposes a `peek` method. ### `chunks` #### Description An adaptor for chunking up items of the stream inside a vector. ### `ready_chunks` #### Description An adaptor for chunking up ready items of the stream inside a vector. ### `inspect` #### Description Do something with each item of this stream, afterwards passing it on. ### `left_stream` #### Description Wrap this stream in an `Either` stream, making it the left-hand variant of that `Either`. ### `right_stream` #### Description Wrap this stream in an `Either` stream, making it the right-hand variant of that `Either`. ``` -------------------------------- ### Set Maximum WebSocket Frame Size Source: https://docs.rs/actix-ws/0.3.0/src/actix_ws/stream.rs.html Configures the maximum permitted size for received WebSocket frames. Defaults to 64KiB. Any frames exceeding this size will result in an error. ```rust use actix_ws::MessageStream; # fn test(stream: MessageStream) { // increase permitted frame size from 64KB to 1MB let stream = stream.max_frame_size(1024 * 1024); # } ``` -------------------------------- ### WebSocket handle function signature Source: https://docs.rs/actix-ws/0.3.0/actix_ws/fn.handle.html The primary function signature for initiating a WebSocket session from an HTTP request. ```rust pub fn handle( req: &HttpRequest, body: Payload, ) -> Result<(HttpResponse, Session, MessageStream), Error> ``` -------------------------------- ### Stream Trait Implementations Source: https://docs.rs/actix-ws/0.3.0/actix_ws/struct.AggregatedMessageStream.html Implementations and extensions for the Stream and TryStream traits. ```APIDOC ## Stream and TryStream Implementations ### `TryFrom for T` #### Description Implementation for converting between types using `TryFrom`. ### `TryInto for T` #### Description Implementation for converting between types using `TryInto`. ### `TryStream` Trait #### Description Trait for streams that yield `Result` items. #### Methods - `try_poll_next`: Poll this `TryStream` as if it were a `Stream`. ### `TryStreamExt` Trait #### Description Extension trait for `TryStream` providing additional utility methods. #### Methods - `err_into`: Wraps the current stream in a new stream which converts the error type into the one provided. - `map_ok`: Wraps the current stream in a new stream which maps the success value using the provided closure. - `map_err`: Wraps the current stream in a new stream which maps the error value using the provided closure. - `and_then`: Chain on a computation for when a value is ready, passing the successful results to the provided closure `f`. - `or_else`: Chain on a computation for when an error happens, passing the erroneous result to the provided closure `f`. - `inspect_ok`: Do something with the success value of this stream, afterwards passing it on. - `inspect_err`: Do something with the error value of this stream, afterwards passing it on. - `into_stream`: Wraps a `TryStream` into a type that implements `Stream`. ``` -------------------------------- ### Stream Transformation and Combination Source: https://docs.rs/actix-ws/0.3.0/actix_ws/struct.MessageStream.html Methods for transforming stream items, combining streams, and handling asynchronous operations within streams. ```APIDOC ## Stream Extension Methods This section details various extension methods available for streams, enabling advanced stream manipulation and asynchronous processing. ### `then(self, f: F) -> Then` **Description**: Computes new items of a different type from this stream's items using an asynchronous closure. **Method**: `then` **Endpoint**: N/A (Method on Stream) ### `collect(self) -> Collect` **Description**: Transforms a stream into a collection, returning a future that represents the result of that computation. **Method**: `collect` **Endpoint**: N/A (Method on Stream) ### `unzip(self) -> Unzip` **Description**: Converts a stream of pairs into a future, which resolves to a pair of containers. **Method**: `unzip` **Endpoint**: N/A (Method on Stream) ### `concat(self) -> Concat` **Description**: Concatenates all items of a stream into a single extendable destination, returning a future that represents the end result. **Method**: `concat` **Endpoint**: N/A (Method on Stream) ### `cycle(self) -> Cycle` **Description**: Repeats a stream endlessly. **Method**: `cycle` **Endpoint**: N/A (Method on Stream) ### `flatten(self) -> Flatten` **Description**: Flattens a stream of streams into a single continuous stream. **Method**: `flatten` **Endpoint**: N/A (Method on Stream) ### `flatten_unordered(self, limit: impl Into>) -> FlattenUnorderedWithFlowController` **Description**: Flattens a stream of streams into a single continuous stream. Polls inner streams produced by the base stream concurrently. **Method**: `flatten_unordered` **Endpoint**: N/A (Method on Stream) ### `flat_map(self, f: F) -> FlatMap` **Description**: Maps a stream like `StreamExt::map` but flattens nested `Stream`s. **Method**: `flat_map` **Endpoint**: N/A (Method on Stream) ### `flat_map_unordered(self, limit: impl Into>, f: F) -> FlatMapUnordered` **Description**: Maps a stream like `StreamExt::map` but flattens nested `Stream`s and polls them concurrently, yielding items in any order, as they become available. **Method**: `flat_map_unordered` **Endpoint**: N/A (Method on Stream) ### `scan(self, initial_state: S, f: F) -> Scan` **Description**: A combinator similar to `StreamExt::fold` that holds internal state and produces a new stream. **Method**: `scan` **Endpoint**: N/A (Method on Stream) ### `skip_while(self, f: F) -> SkipWhile` **Description**: Skips elements on this stream while the provided asynchronous predicate resolves to `true`. **Method**: `skip_while` **Endpoint**: N/A (Method on Stream) ### `take_while(self, f: F) -> TakeWhile` **Description**: Takes elements from this stream while the provided asynchronous predicate resolves to `true`. **Method**: `take_while` **Endpoint**: N/A (Method on Stream) ### `take_until(self, fut: Fut) -> TakeUntil` **Description**: Takes elements from this stream until the provided future resolves. **Method**: `take_until` **Endpoint**: N/A (Method on Stream) ### `take(self, n: usize) -> Take` **Description**: Creates a new stream of at most `n` items of the underlying stream. **Method**: `take` **Endpoint**: N/A (Method on Stream) ### `skip(self, n: usize) -> Skip` **Description**: Creates a new stream which skips `n` items of the underlying stream. **Method**: `skip` **Endpoint**: N/A (Method on Stream) ``` -------------------------------- ### Aggregate WebSocket Continuation Frames Source: https://docs.rs/actix-ws/0.3.0/src/actix_ws/stream.rs.html Wraps a MessageStream to collect continuation frames into aggregated binary or text messages. By default, continuations are aggregated up to 1MiB. ```rust use actix_ws::MessageStream; use actix_ws::AggregatedMessageStream; # fn test(stream: MessageStream) { let aggregated_stream = stream.aggregate_continuations(); # } ``` -------------------------------- ### WebSocket Session Methods Source: https://docs.rs/actix-ws/0.3.0/actix_ws/struct.Session.html Methods available on the Session struct to manage WebSocket communication. ```APIDOC ## text ### Description Sends text into the WebSocket. ### Parameters - **msg** (impl Into) - Required - The text message to send. ### Response - **Result<(), Closed>** - Returns Ok if successful, or Err(Closed) if the session is closed. ## binary ### Description Sends raw bytes into the WebSocket. ### Parameters - **msg** (impl Into) - Required - The binary data to send. ### Response - **Result<(), Closed>** - Returns Ok if successful, or Err(Closed) if the session is closed. ## ping ### Description Pings the client to keep the connection alive. ### Parameters - **msg** (&[u8]) - Required - The ping payload. ### Response - **Result<(), Closed>** - Returns Ok if successful, or Err(Closed) if the session is closed. ## pong ### Description Pongs the client in response to a ping. ### Parameters - **msg** (&[u8]) - Required - The pong payload. ### Response - **Result<(), Closed>** - Returns Ok if successful, or Err(Closed) if the session is closed. ## continuation ### Description Manually controls sending continuations for fragmented messages. ### Parameters - **msg** (Item) - Required - The continuation item (First, Continue, or Last). ### Response - **Result<(), Closed>** - Returns Ok if successful, or Err(Closed) if the session is closed. ## close ### Description Sends a close message and consumes the session. ### Parameters - **reason** (Option) - Optional - The reason for closing the connection. ### Response - **Result<(), Closed>** - Returns Ok if successful, or Err(Closed) if the session is already closed. ``` -------------------------------- ### Configure Maximum Frame Size Source: https://docs.rs/actix-ws/0.3.0/actix_ws/struct.MessageStream.html Sets the maximum permitted size for received WebSocket frames in bytes. Exceeding this limit results in a ProtocolError::Overflow. ```rust // increase permitted frame size from 64KB to 1MB let stream = stream.max_frame_size(1024 * 1024); ``` -------------------------------- ### Implement Instrument for T Source: https://docs.rs/actix-ws/0.3.0/actix_ws/enum.Item.html Enables instrumenting a type with a Span for tracing. ```rust fn instrument(self, span: Span) -> Instrumented ``` ```rust fn in_current_span(self) -> Instrumented ``` -------------------------------- ### Stream Aggregation and Predicates Source: https://docs.rs/actix-ws/0.3.0/actix_ws/struct.MessageStream.html Methods for aggregating stream data, counting elements, and applying predicates. ```APIDOC ### `count(self) -> Count` **Description**: Drives the stream to completion, counting the number of items. **Method**: `count` **Endpoint**: N/A (Method on Stream) ### `fold(self, init: T, f: F) -> Fold` **Description**: Executes an accumulating asynchronous computation over a stream, collecting all the values into one final result. **Method**: `fold` **Endpoint**: N/A (Method on Stream) ### `any(self, f: F) -> Any` **Description**: Executes a predicate over an asynchronous stream and returns `true` if any element in the stream satisfied the predicate. **Method**: `any` **Endpoint**: N/A (Method on Stream) ### `all(self, f: F) -> All` **Description**: Executes a predicate over an asynchronous stream and returns `true` if all elements in the stream satisfied the predicate. **Method**: `all` **Endpoint**: N/A (Method on Stream) ### `for_each(self, f: F) -> ForEach` **Description**: Runs this stream to completion, executing the provided asynchronous closure for each element on the stream. **Method**: `for_each` **Endpoint**: N/A (Method on Stream) ### `for_each_concurrent(self, limit: impl Into>, f: F) -> ForEachConcurrent` **Description**: Runs this stream to completion, executing the provided asynchronous closure for each element on the stream concurrently as elements become available. **Method**: `for_each_concurrent` **Endpoint**: N/A (Method on Stream) ``` -------------------------------- ### Implement Same for T Source: https://docs.rs/actix-ws/0.3.0/actix_ws/enum.Item.html Defines the output type for the Same trait, which should always be Self. ```rust type Output = T ``` -------------------------------- ### Attach current default subscriber to type Source: https://docs.rs/actix-ws/0.3.0/actix_ws/struct.MessageStream.html Attaches the currently configured default `Subscriber` to the type, returning a `WithDispatch` wrapper. This is a convenient method for applying the global subscriber. ```rust fn with_current_subscriber(self) -> WithDispatch ``` -------------------------------- ### Implement TryFrom for T Source: https://docs.rs/actix-ws/0.3.0/actix_ws/enum.Item.html Enables fallible conversion from U to T, with an Infallible error type. ```rust type Error = Infallible ``` ```rust fn try_from(value: U) -> Result>::Error> ``` -------------------------------- ### Close session Source: https://docs.rs/actix-ws/0.3.0/actix_ws/struct.Session.html Sends a close message and consumes the session instance. ```rust session.close(None).await ``` -------------------------------- ### TryStream Extensions Source: https://docs.rs/actix-ws/0.3.0/actix_ws/struct.MessageStream.html Methods for handling streams that yield Result types, allowing for error mapping and chaining. ```APIDOC ## TryStream Extensions ### Description Extensions for streams yielding Result to facilitate error handling and transformation. ### Methods - **err_into()**: Converts the error type into the provided type E. - **map_ok(f)**: Maps the success value using closure f. - **map_err(f)**: Maps the error value using closure f. - **and_then(f)**: Chains a computation for successful results. - **or_else(f)**: Chains a computation for error results. ``` -------------------------------- ### Attach subscriber to type Source: https://docs.rs/actix-ws/0.3.0/actix_ws/struct.MessageStream.html Attaches a provided `Subscriber` to the current type, returning a `WithDispatch` wrapper. The subscriber must be convertible into a `Dispatch` type. ```rust fn with_subscriber(self, subscriber: S) -> WithDispatch where S: Into, ``` -------------------------------- ### Type Conversion Error Handling Source: https://docs.rs/actix-ws/0.3.0/actix_ws/struct.Session.html Details the error type returned during conversion attempts. ```APIDOC ## Type Conversion Error ### Description The type returned in the event of a conversion error. ### Type Alias `Error = >::Error` ### Method `try_into(self) -> Result>::Error>` Performs the conversion. Returns a `Result` which is either the converted value or the conversion error. ``` -------------------------------- ### Execute predicate over stream, check if all items satisfy Source: https://docs.rs/actix-ws/0.3.0/actix_ws/struct.MessageStream.html Attempts to execute a predicate function on each item of an asynchronous stream. It returns `true` if all items satisfy the predicate, and `false` otherwise. The operation exits early if an error is encountered or if an item does not satisfy the predicate. ```rust fn try_all(self, f: F) -> TryAll where Self: Sized, F: FnMut(Self::Ok) -> Fut, Fut: Future, ``` -------------------------------- ### Instrument Trait Methods Source: https://docs.rs/actix-ws/0.3.0/actix_ws/enum.CloseCode.html Methods for instrumenting types with spans for tracing. ```APIDOC ## Instrument Trait ### Description Instruments a type with a Span or the current Span. ### Methods - **instrument(self, span: Span) -> Instrumented** - **in_current_span(self) -> Instrumented** ``` -------------------------------- ### WithSubscriber Trait Methods Source: https://docs.rs/actix-ws/0.3.0/actix_ws/enum.CloseCode.html Methods for attaching subscribers to types. ```APIDOC ## WithSubscriber Trait ### Description Attaches a subscriber to a type for dispatching. ### Methods - **with_subscriber(self, subscriber: S) -> WithDispatch** - **with_current_subscriber(self) -> WithDispatch** ``` -------------------------------- ### Stream Utility Methods Source: https://docs.rs/actix-ws/0.3.0/actix_ws/struct.MessageStream.html Methods for polling and evaluating predicates over asynchronous streams. ```APIDOC ## fn try_poll_next_unpin ### Description A convenience method for calling `TryStream::try_poll_next` on `Unpin` stream types. ## fn try_all ### Description Attempt to execute a predicate over an asynchronous stream and evaluate if all items satisfy the predicate. Exits early if an `Err` is encountered or if an `Ok` item is found that does not satisfy the predicate. ## fn try_any ### Description Attempt to execute a predicate over an asynchronous stream and evaluate if any items satisfy the predicate. Exits early if an `Err` is encountered or if an `Ok` item is found that satisfies the predicate. ``` -------------------------------- ### Stream Filtering and Predicates Source: https://docs.rs/actix-ws/0.3.0/actix_ws/struct.AggregatedMessageStream.html Methods for evaluating stream elements against asynchronous predicates. ```APIDOC ## any ### Description Execute predicate over asynchronous stream, and return true if any element in stream satisfied a predicate. ## all ### Description Execute predicate over asynchronous stream, and return true if all element in stream satisfied a predicate. ## skip_while ### Description Skip elements on this stream while the provided asynchronous predicate resolves to true. ## take_while ### Description Take elements from this stream while the provided asynchronous predicate resolves to true. ``` -------------------------------- ### Send binary message Source: https://docs.rs/actix-ws/0.3.0/actix_ws/struct.Session.html Sends raw bytes through the WebSocket session. ```rust if session.binary(&b"some bytes"[..]).await.is_err() { // session closed } ``` -------------------------------- ### Send ping frame Source: https://docs.rs/actix-ws/0.3.0/actix_ws/struct.Session.html Sends a ping frame to the client to verify connection status. ```rust if session.ping(b"").await.is_err() { // session is closed } ``` -------------------------------- ### TryStream Extensions Source: https://docs.rs/actix-ws/0.3.0/actix_ws/struct.StreamingBody.html Extensions for streams that yield Result types, allowing for error handling and chaining. ```APIDOC ## TryStream Extensions ### Description Utilities for processing streams that yield Result, including mapping, chaining, and error handling. ### Methods - **err_into()**: Converts the error type into the provided type E. - **map_ok(f: F)**: Maps the success value using the provided closure. - **map_err(f: F)**: Maps the error value using the provided closure. - **and_then(f: F)**: Chains a computation for successful results. - **or_else(f: F)**: Chains a computation for error results. - **inspect_ok(f: F)**: Inspects success values. - **inspect_err(f: F)**: Inspects error values. - **try_next()**: Future that resolves the next item or returns an error. - **try_for_each(f: F)**: Runs the stream to completion with an async closure. ``` -------------------------------- ### Execute predicate over stream, check if any item satisfies Source: https://docs.rs/actix-ws/0.3.0/actix_ws/struct.MessageStream.html Attempts to execute a predicate function on each item of an asynchronous stream. It returns `true` if at least one item satisfies the predicate, and `false` otherwise. The operation exits early if an error is encountered or if an item satisfies the predicate. ```rust fn try_any(self, f: F) -> TryAny where Self: Sized, F: FnMut(Self::Ok) -> Fut, Fut: Future, ``` -------------------------------- ### Item Enum Trait Implementations Source: https://docs.rs/actix-ws/0.3.0/actix_ws/enum.Item.html Details the trait implementations for the Item enum, including Debug, PartialEq, and Eq. ```APIDOC ## Item Enum Trait Implementations ### Debug Provides a way to format the Item enum for debugging purposes. ### PartialEq Allows comparison of two Item instances for equality. ### Eq Indicates that equality is an equivalence relation for the Item enum. ``` -------------------------------- ### VZip Trait Implementation Source: https://docs.rs/actix-ws/0.3.0/actix_ws/struct.Session.html Implementation of the VZip trait for multi-lane types. ```rust impl VZip for T where V: MultiLane, ``` ```rust fn vzip(self) -> V ```