Skip to main content

Client

Struct Client 

Source
pub struct Client<S: AppState> {
    pub signal: Signals,
    pub state: Arc<S>,
    pub module_handles: Arc<RwLock<HashMap<TypeId, Box<dyn Any + Send + Sync>>>>,
    pub to_ws_sender: AsyncSender<Message>,
    /* private fields */
}

Fields§

§signal: Signals§state: Arc<S>

The shared application state, which can be used by modules and handlers.

§module_handles: Arc<RwLock<HashMap<TypeId, Box<dyn Any + Send + Sync>>>>§to_ws_sender: AsyncSender<Message>

Implementations§

Source§

impl<S: AppState> Client<S>

Source

pub fn new( signal: Signals, runner_command_tx: AsyncSender<RunnerCommand>, state: Arc<S>, sender: AsyncSender<Message>, ) -> Self

Source

pub async fn wait_connected(&self)

Waits until the client is connected to the WebSocket server. This method will block until the connection is established. It is useful for ensuring that the client is ready to send and receive messages.

Source

pub fn is_connected(&self) -> bool

Checks if the client is connected to the WebSocket server.

Source

pub async fn get_handle<M: ApiModule<S>>(&self) -> Option<M::Handle>

Retrieves a clonable, typed handle to an already-registered module.

Examples found in repository?
examples/echo_client.rs (line 318)
317    pub async fn echo(&self, msg: String) -> CoreResult<String> {
318        match self.client.get_handle::<EchoModule>().await {
319            Some(echo_handle) => echo_handle.echo(msg).await,
320            None => Err(CoreError::ModuleNotFound("EchoModule".to_string())),
321        }
322    }
323
324    pub async fn stream(&self) -> CoreResult<impl Stream<Item = CoreResult<String>>> {
325        let stream_handle = self.client.get_handle::<StreamModule>().await.unwrap();
326        println!("Starting stream...");
327        stream_handle.stream().await
328    }
329
330    pub async fn start(&self) -> CoreResult<()> {
331        match self.client.get_handle::<PeriodicSenderModule>().await {
332            Some(handle) => {
333                handle.start().await;
334                Ok(())
335            }
336            None => Err(CoreError::ModuleNotFound(
337                stringify!(PeriodicSenderModule).to_string(),
338            )),
339        }
340    }
More examples
Hide additional examples
examples/testing_echo_client.rs (line 167)
163    pub async fn echo(&self, msg: String) -> CoreResult<String> {
164        match self
165            .testing_wrapper
166            .client()
167            .get_handle::<EchoModule>()
168            .await
169        {
170            Some(echo_handle) => echo_handle.echo(msg).await,
171            None => Err(CoreError::ModuleNotFound("EchoModule".to_string())),
172        }
173    }
Source

pub async fn disconnect(&self) -> CoreResult<()>

Commands the runner to disconnect, clear state, and perform a “hard” reconnect.

Source

pub async fn reconnect(&self) -> CoreResult<()>

Commands the runner to disconnect, and perform a “soft” reconnect.

Source

pub async fn shutdown(self) -> CoreResult<()>

Commands the runner to shutdown, this action is final as the runner and client will stop working and will be dropped.

Examples found in repository?
examples/middleware_example.rs (line 236)
219async fn main() -> CoreResult<()> {
220    // Initialize tracing
221    tracing_subscriber::fmt::init();
222
223    // Create statistics middleware
224    let stats_middleware = Arc::new(StatisticsMiddleware::new());
225
226    // Build the client with middleware
227    let (client, _) = ClientBuilder::new(MockConnector, ExampleState)
228        .with_middleware(Box::new(LoggingMiddleware))
229        .with_middleware(Box::new(StatisticsMiddleware::new()))
230        .with_module::<ExampleModule>()
231        .build()
232        .await?;
233
234    info!("Client built with middleware layers");
235    tokio::time::sleep(Duration::from_secs(10)).await;
236    client.shutdown().await?;
237    // In a real application, you would:
238    // 1. Start the runner in a background task
239    // 2. Use the client to send messages
240    // 3. Check statistics periodically
241
242    // For demonstration, we'll just show the statistics
243    let stats = stats_middleware.get_stats();
244    info!("Current statistics: {:?}", stats);
245
246    Ok(())
247}
Source

pub async fn shutdown_ref(&self) -> CoreResult<()>

Commands the runner to shutdown without consuming the client.

Source

pub async fn send_message(&self, message: Message) -> CoreResult<()>

Send a message to the WebSocket

Source

pub async fn send_text(&self, text: String) -> CoreResult<()>

Send a text message to the WebSocket

Source

pub async fn send_binary(&self, data: Vec<u8>) -> CoreResult<()>

Send a binary message to the WebSocket

Trait Implementations§

Source§

impl<S: AppState> Clone for Client<S>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 · Source§

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

Performs copy-assignment from source. Read more
Source§

impl<S: Debug + AppState> Debug for Client<S>

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl<S> Freeze for Client<S>

§

impl<S> !RefUnwindSafe for Client<S>

§

impl<S> Send for Client<S>

§

impl<S> Sync for Client<S>

§

impl<S> Unpin for Client<S>

§

impl<S> UnsafeUnpin for Client<S>

§

impl<S> !UnwindSafe for Client<S>

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 = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

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

Source§

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

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

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

Performs the conversion.
Source§

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

Source§

fn vzip(self) -> V

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