Skip to main content

Sender

Struct Sender 

Source
pub struct Sender { /* private fields */ }
Expand description

Entry point for sending messages, permanently bound to the session that created it; clones continue to share that session.

Obtain a sender from super::Session::sender and distribute it to multiple application tasks. The application must still retain the original super::Session: dropping the session cancels it, and retaining a sender cannot prevent shutdown. The sender remains usable after that session reconnects; a newly created session requires a new sender.

Use Self::send when only the local write result matters, Self::enqueue when the operation must be tracked or cancelled separately, and Self::try_enqueue when waiting for queue capacity is not possible. Configure per-message priority, deadlines, and related settings through Self::message.

Implementations§

Source§

impl Sender

Source

pub fn session_id(&self) -> SessionId

Returns the logical session identifier to which this sender is bound.

§Use cases

Associate application logs and send receipts with the correct session when several sessions run in parallel. Cloning the sender or reconnecting the same session does not change this identifier; it does not identify any particular physical connection.

§Example
use open_net::ws::Session;

fn log_sender(session: &Session) {
    let sender = session.sender();
    assert_eq!(sender.session_id(), session.id());
    println!("Sender session: {}", sender.session_id());
}
Source

pub fn is_closed(&self) -> bool

Checks whether the owning session has been cancelled or terminated, or the client has requested shutdown.

§Use cases

Quickly decide whether to stop producing messages before constructing more work for a finished session. A false result does not mean that the session is currently connected: it may still be connecting or waiting to reconnect. Initiating a graceful session close does not guarantee an immediate true; wait for the session close result to confirm that it has ended. The session can still close between this check and a send, so always handle errors returned by the sending methods.

§Example
use open_net::{ws::Sender, Result};

async fn publish_status(sender: &Sender) -> Result<()> {
    if sender.is_closed() {
        return Ok(()); // The session has ended; stop this status update.
    }
    sender.send("status:online").await?;
    Ok(())
}
Source

pub fn message(&self, message: impl Into<Message>) -> MessageBuilder

Creates a builder holding the message body, initially using SendOptions::default.

This method only constructs the message; it does not reserve queue capacity or send it. Strings become text messages, while byte slices, Vec<u8>, and similar values become binary messages. A Message can also be supplied explicitly.

§Use cases

When a message needs a custom priority, enqueue timeout, disconnection policy, or cancellation group, create a builder first, then configure it with MessageBuilder::options and choose whether to send or reserve its resources.

§Example
use open_net::{
    ws::{Priority, SendOptions, Sender},
    Result,
};
use std::time::Duration;

async fn publish_alert(sender: &Sender) -> Result<()> {
    sender
        .message("alert:temperature-high")
        .options(SendOptions {
            priority: Priority::High,
            enqueue_timeout: Some(Duration::from_secs(1)),
            ..Default::default()
        })
        .send()
        .await
}
Source

pub async fn send(&self, message: impl Into<Message>) -> Result<()>

Uses the default sending policy, waits for the message to be queued, and waits for the local WebSocket write to complete.

Equivalent to self.message(message).send().await. By default, sending is rejected when disconnected, capacity shortages are awaited without a separate enqueue timeout, and each write attempt has a 10-second limit with no retry. Success confirms only the local write; it does not confirm that the server received or processed the message.

§Use cases

Suitable for simple sequential flows such as status notifications or chat messages, where the next step follows the local write. Errors such as disconnection, session closure, or a write timeout are returned directly. This interface does not retain a failed message for retrieval; use Self::enqueue when enqueue failures must preserve the message or the operation must be cancelled explicitly.

§Example
use open_net::error::ReceiveError;
use open_net::network::{NetworkConfig, NetworkStatusPolicy};
use open_net::subscription::{CallbackContext, Subscription};
use open_net::ws::{
    ConnectOptions, ConnectionEvent, ConnectionEventKind, ConnectionSnapshot, HeartbeatConfig,
    IncomingMessage, Message, RetryDecision, TaskEvent, TaskEventOptions, TcpKeepaliveConfig,
    WebSocketClientConfig,
};
use open_net::{HeaderValue, OpenNet, OpenNetConfig};
use std::thread;
use std::time::Duration;

let net = OpenNet::new_with_config(OpenNetConfig::default().with_runtime_worker_threads(2))?;
let mut config = WebSocketClientConfig::default();
config.queues.normal.max_items = 128;
config.queues.urgent.max_items = 32;
config.requests.max_pending = 128;
config.frames.max_message_size = Some(8 * 1024 * 1024);
config.frames.data_frame_payload_size = Some(32 * 1024); // Large messages are framed automatically.
config.tcp.nodelay = true;
config.tcp.keepalive = Some(TcpKeepaliveConfig::default());
// The SDK handles Ping/Pong; the application does not need to emulate PB heartbeats with control frames.
config.heartbeat = Some(HeartbeatConfig {
    interval: Duration::from_secs(20),
    pong_timeout: Duration::from_secs(45),
});
config.close_timeout = Duration::from_secs(2);
config.validate()?;

let network = NetworkConfig::default().with_network_status_policy(NetworkStatusPolicy::Ignore);
// Explicitly override the client network configuration here; the default is direct access,
// and wss uses the default trusted root certificates.
// Other creation methods: net.create_ws_client(CLIENT_NAME).await?;
// net.create_ws_client_with_config(CLIENT_NAME, config).await?.
let client = net
    .create_ws_client_with_network_config("ws_1_thread_name", config, network)
    .await?;
let _shared = net.get_ws_client("ws_1_thread_name")?; // Like clone(), this points to the same client.

let mut options = ConnectOptions::new(WS_BASE_URL);
options.headers.insert(
    "authorization",
    HeaderValue::from_static("Bearer example-token"),
);
options
    .headers
    .insert("x-client-name", HeaderValue::from_static("demo"));

let current_thread = thread::current();
// A-thread_name: main, thread_id: ThreadId(1)
println!(
    "A-thread_name: {}, thread_id: {:?}",
    current_thread.name().unwrap_or("unnamed"),
    current_thread.id()
);
let mut session = client.connect(options).await?;

// Keep subscription handles alive until the function returns; dropping a handle unsubscribes it.
let _state_subscription: Subscription = session.on_state(
    |context: CallbackContext, state: open_net::Result<ConnectionSnapshot>| match state {
        Ok(state) => {
            let current_thread = thread::current();
            //  thread_name: open-net-ws-status-0, thread_id: ThreadId(18)
            println!(
                "State callback[{}]: {state:?}, thread_name: {}, thread_id: {:?}",
                context.id(),
                current_thread.name().unwrap_or("unnamed"),
                current_thread.id()
            );
        }
        Err(error) => {
            eprintln!("Failed to receive state[{}]: {error}", context.id())
        }
    },
)?;

let callback_sender = session.sender();
let _message_subscription: Subscription = session.on_message(
    move |context: CallbackContext, message: Result<IncomingMessage, ReceiveError>| {
        match message {
            Ok(message) => {
                // thread_name: open-net-ws-data-callback, thread_id: ThreadId(20)
                let current_thread = thread::current();
                println!("message_subscription->IncomingMessage: {:?}, thread_name: {}, thread_id: {:?}", message,
                         current_thread.name().unwrap_or("unnamed"),
                         current_thread.id());
            }
            Err(error) => {
                println!("message_subscription->error: {}", error);
            }
        }
    },
)?;

let _event_subscription: Subscription = session.on_event(
    |context: CallbackContext, event: Result<ConnectionEvent, ReceiveError>| match event {
        Ok(event) => {
            //  thread_name: open-net-ws-events-1, thread_id: ThreadId(22)
            let current_thread = thread::current();
            println!(
                "Connection event[{}] #{}: client={} session={} at={:?}, thread_name: {}, thread_id: {:?}",
                context.id(),
                event.sequence,
                event.client_id,
                event.session_id,
                event.occurred_at,
                current_thread.name().unwrap_or("unnamed"),
                current_thread.id());
            // on_event records lifecycle events; observe immediate states such as network waits through on_state.
            match event.kind {
                ConnectionEventKind::AttemptStarted { attempt } => {
                    println!(
                        "           Starting connection attempt: cycle={} attempt={} (initial connection or retry)",
                        attempt.cycle_id, attempt.attempt_id
                    );
                }
                ConnectionEventKind::Established { connection } => {
                    println!(
                        "           Connection established: connection={} cycle={} attempt={} connected_at={:?}",
                        connection.connection_id,
                        connection.cycle_id,
                        connection.attempt_id,
                        connection.connected_at
                    );
                }
                ConnectionEventKind::AttemptFailed {
                    attempt,
                    error,
                    retry,
                    ..
                } => {
                    eprintln!(
                        "           Connection attempt failed: cycle={} attempt={} kind={:?} stage={:?} error={error}",
                        attempt.cycle_id,
                        attempt.attempt_id,
                        error.kind(),
                        error.context().stage
                    );
                    match retry {
                        RetryDecision::Scheduled { after } => {
                            println!(
                                "           Retry scheduled: trying to connect again after a backoff of {} ms",
                                after.as_millis()
                            );
                        }
                        RetryDecision::Stop => {
                            println!("          Stopping retries; waiting for the session-closed event");
                        }
                    }
                }
                ConnectionEventKind::Disconnected { connection, end } => {
                    // A single connection can disconnect and still reconnect; Closed marks the end of the session.
                    println!(
                        "               Connection disconnected: connection={} reason={:?} io_end={:?}",
                        connection.connection_id, end.reason, end.io_end
                    );
                    if let Some(close) = end.peer_close {
                        println!(
                            "           Peer close information: code={:?} reason={}",
                            close.code, close.reason
                        );
                    }
                    if let Some(error) = end.error {
                        eprintln!("         Disconnection error: kind={:?} error={error}", error.kind());
                    }
                }
                ConnectionEventKind::Closed { result } => match result {
                    Ok(end) => {
                        println!("          Session closed; will not reconnect: reason={:?}", end.reason);
                        if let Some(last) = end.last_connection {
                            println!("          Last connection end information: {last:?}");
                        }
                    }
                    Err(error) => {
                        eprintln!(
                            "           Session ended unexpectedly; will not reconnect: kind={:?} error={error}",
                            error.kind()
                        );
                    }
                },
                // ConnectionEventKind is marked non_exhaustive to support future event variants.
                other => println!("         Other connection event: {other:?}"),
            }
        }
        Err(error) => eprintln!("           Failed to receive connection event[{}]: {error}", context.id()),
    },
)?;

let _task_subscription: Subscription = session.on_task(
    TaskEventOptions::default(),
    |context: CallbackContext, event: Result<TaskEvent, ReceiveError>| match event {
        Ok(event) => {
            // thread_name: open-net-task-events-1-0, thread_id: ThreadId(23)
            let current_thread = thread::current();
            println!(
                "Task callback[{}]: {event:?}, thread_name: {}, thread_id: {:?}",
                context.id(),
                current_thread.name().unwrap_or("unnamed"),
                current_thread.id()
            );
        }
        Err(error) => eprintln!("Failed to receive task event[{}]: {error}", context.id()),
    },
)?;

let sender = session.sender();

// Omit the code for building the PB protocol
let message = Message::text("demo:message");
sender.send(message).await?;

thread::sleep(Duration::from_secs(15));

let shutdown = client.shutdown().await; // Permanently closes the client; no clone can reconnect.
let destroy = net.destroy_ws_client("ws_1_thread_name").await; // Also removes the registered name from the engine.
println!(
    "Client closed={}, shutdown={shutdown:?}, destroy={destroy:?}",
    client.is_shutdown()
);
shutdown?;
destroy?;
Source

pub async fn enqueue( &self, message: impl Into<Message>, ) -> Result<MessageReceipt, EnqueueError<Message>>

Uses the default sending policy, waits for capacity, and returns a trackable receipt as soon as the message is submitted.

Success means only that the message was enqueued; use MessageReceipt::written to wait for the local write. Capacity covers both the send queue and resources needed for subscribed operation events, so a slow consumer can create backpressure. By default no enqueue timeout is set and sending is rejected while disconnected; use Self::message to change these policies.

§Use cases

Suitable when production and completion tracking are separate: the producer continues after submission while another task retains the receipt to query status or cancel. A failed EnqueueError retains the converted Message; use EnqueueError::into_parts to recover the body and decide whether to cache, discard, or resubmit it later.

§Example
use open_net::{
    ws::{Message, MessageReceipt, Sender},
    Result,
};

async fn enqueue_report(
    sender: &Sender,
    pending: &mut Vec<MessageReceipt>,
    unsent: &mut Vec<Message>,
) -> Result<()> {
    match sender.enqueue("report:ready").await {
        Ok(receipt) => pending.push(receipt), // Wait for written() later as a group.
        Err(failure) => {
            let (message, error) = failure.into_parts();
            unsent.push(message); // Preserve the body that was never enqueued.
            return Err(error);
        }
    }
    Ok(())
}
Source

pub fn try_enqueue( &self, message: impl Into<Message>, ) -> Result<MessageReceipt, EnqueueError<Message>>

Attempts to enqueue immediately with the default sending policy, without waiting for capacity or write completion.

Returns crate::error::ErrorKind::QueueFull when queue or operation-event resources are temporarily exhausted. It can also fail because the client is disconnected, the session is closed, the message is too large, or for other reasons. The converted message is retained on failure. This synchronous entry point does not require the calling thread to enter a Tokio runtime, but the client worker tasks must remain alive.

§Use cases

Suitable for UI events, synchronous callbacks, and collection paths that cannot wait for backpressure. The application can cache or coalesce messages when the queue is full; do not treat every error as queue-full and retry unconditionally.

§Example
use open_net::{error::ErrorKind, ws::{Message, MessageReceipt, Sender}, Result};

fn submit_sample(
    sender: &Sender,
    backlog: &mut Vec<Message>,
) -> Result<Option<MessageReceipt>> {
    match sender.try_enqueue("temperature:24") {
        Ok(receipt) => Ok(Some(receipt)),
        Err(failure) if failure.error().kind() == ErrorKind::QueueFull => {
            backlog.push(failure.into_inner()); // The application controls cache bounds and retry timing.
            Ok(None)
        }
        Err(failure) => Err(failure.into_error()),
    }
}

Trait Implementations§

Source§

impl Clone for Sender

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Sender

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

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

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

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

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

fn in_current_span(self) -> Instrumented<Self> ⓘ

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

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

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

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

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

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

Source§

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

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

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