Struct socketio_rs::Client

source ·
pub struct Client { /* private fields */ }

Implementations

Sends a message to the server using the underlying engine.io protocol. This message takes an event, which could either be one of the common events like “message” or “error” or a custom event like “foo”. But be careful, the data string needs to be valid JSON. It’s recommended to use a library like serde_json to serialize the data properly.

Example
use socketio_rs::{ClientBuilder, Socket, AckId, Payload};
use serde_json::json;
use futures_util::FutureExt;

#[tokio::main]
async fn main() {
    let mut socket = ClientBuilder::new("http://localhost:4200/")
        .on("test", |payload: Option<Payload>, socket: Socket, need_ack: Option<AckId>| {
            async move {
                println!("Received: {:?}", payload);
                socket.emit("test", json!({"hello": true})).await.expect("Server unreachable");
            }.boxed()
        })
        .connect()
        .await
        .expect("connection failed");

    let json_payload = json!({"token": 123});

    let result = socket.emit("foo", json_payload).await;

    assert!(result.is_ok());
}

Sends a message to the server but allocs an ack to check whether the server responded in a given time span. This message takes an event, which could either be one of the common events like “message” or “error” or a custom event like “foo”, as well as a data parameter. It also requires a timeout Duration in which the client needs to answer. If the ack is acked in the correct time span, the specified callback is called. The callback consumes a Payload which represents the data send by the server.

Please note that the requirements on the provided callbacks are similar to the ones for [crate::asynchronous::ClientBuilder::on].

Example
use socketio_rs::{ClientBuilder, Socket, Payload};
use serde_json::json;
use std::time::Duration;
use std::thread::sleep;
use futures_util::FutureExt;

#[tokio::main]
async fn main() {
    let mut socket = ClientBuilder::new("http://localhost:4200/")
        .on("foo", |payload: Option<Payload>, _, _| async move { println!("Received: {:#?}", payload) }.boxed())
        .connect()
        .await
        .expect("connection failed");

    let ack_callback = |message: Option<Payload>, socket: Socket, _| {
        async move {
            match message {
                Some(Payload::Json(data)) => println!("{:?}", data),
                Some(Payload::Binary(bytes)) => println!("Received bytes: {:#?}", bytes),
                Some(Payload::Multi(multi)) => println!("Received multi: {:?}", multi),
                _ => {}
            }
        }.boxed()
    };    


    let payload = json!({"token": 123});
    socket.emit_with_ack("foo", payload, Duration::from_secs(2), ack_callback).await.unwrap();

    sleep(Duration::from_secs(2));
}

Disconnects from the server by sending a socket.io Disconnect packet. This results in the underlying engine.io transport to get closed as well.

Trait Implementations

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more

Auto Trait Implementations

Blanket Implementations

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

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

Calls U::from(self).

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

Should always be Self
The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.
Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more