Skip to main content

Client

Struct Client 

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

A socket which handles communication with the server. It’s initialized with a specific address as well as an optional namespace to connect to. If None is given the client will connect to the default namespace "/".

Implementations§

Source§

impl Client

Source

pub async fn emit<E, D>(&self, event: E, data: D) -> Result<(), Error>
where E: Into<Event>, D: Into<Payload>,

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 tf_rust_socketio::{asynchronous::{ClientBuilder, Client}, 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: Payload, socket: Client| {
            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());
}
Source

pub async fn ack<D>(&self, data: D) -> Result<(), Error>
where D: Into<Payload>,

When receive server’s emitwithack callback event, invoke socket.ack(..) function can react to server with ack signal use futures_util::FutureExt;

§Example
use futures_util::FutureExt;
use tf_rust_socketio::{asynchronous::{ClientBuilder, Client}, Payload};
use serde_json::json;
use std::time::Duration;
use std::thread;
use bytes::Bytes;

#[tokio::main]
async fn main() {

    let callback = |payload: Payload, socket: Client| {
       async move {
          match payload {
              Payload::Text(values, ack_id) => {
                  println!("{:#?}", values);
                  if let Some(id) = ack_id {
                      let _ = socket.ack_with_id(id, json!({"status": "received"})).await;
                  }
              },
              Payload::Binary(bytes, ack_id) => {
                  println!("Received bytes: {:#?}", bytes);
                  if let Some(id) = ack_id {
                      let _ = socket.ack_with_id(id, vec![4, 5, 6]).await;
                  }
              },
              Payload::String(str, ack_id) => {
                  println!("{}", str);
                  if let Some(id) = ack_id {
                      let _ = socket.ack_with_id(id, "response").await;
                  }
              },
          }
       }.boxed()
    };

    // get a socket that is connected to the admin namespace
    let socket = ClientBuilder::new("http://localhost:4200")
        .namespace("/")
        .on("foo", callback)
        .on("error", |err, _| {
            async move { eprintln!("Error: {:#?}", err) }.boxed()
        })
        .connect()
        .await
        .expect("Connection failed");
     

    thread::sleep(Duration::from_millis(30000));
    socket.disconnect().await.expect("Disconnect failed");
}
Source

pub async fn ack_with_id<D>(&self, ack_id: i32, data: D) -> Result<(), Error>
where D: Into<Payload>,

Acknowledge a message with a specific ack_id

Source

pub async fn disconnect(&self) -> Result<(), Error>

Disconnects this client from the server by sending a socket.io closing packet.

§Example
use tf_rust_socketio::{asynchronous::{ClientBuilder, Client}, Payload};
use serde_json::json;
use futures_util::{FutureExt, future::BoxFuture};

#[tokio::main]
async fn main() {
    // apparently the syntax for functions is a bit verbose as rust currently doesn't
    // support an `AsyncFnMut` type that conform with async functions
    fn handle_test(payload: Payload, socket: Client) -> BoxFuture<'static, ()> {
        async move {
            println!("Received: {:#?}", payload);
            socket.emit("test", json!({"hello": true})).await.expect("Server unreachable");
        }.boxed()
    }

    let mut socket = ClientBuilder::new("http://localhost:4200/")
        .on("test", handle_test)
        .connect()
        .await
        .expect("connection failed");

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

    socket.emit("foo", json_payload).await;

    // disconnect from the server
    socket.disconnect().await;
}
Source

pub async fn emit_with_ack<F, E, D>( &self, event: E, data: D, timeout: Duration, callback: F, ) -> Result<(), Error>
where F: for<'a> FnMut(Payload, Client) -> BoxFuture<'static, ()> + 'static + Send + Sync, E: Into<Event>, D: Into<Payload>,

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. But be careful, in case you send a Payload::String, the string needs to be valid JSON. It’s even recommended to use a library like serde_json to serialize the data properly. 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 tf_rust_socketio::{asynchronous::{ClientBuilder, Client}, 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: Payload, _| async move { println!("Received: {:#?}", payload) }.boxed())
        .connect()
        .await
        .expect("connection failed");

    let ack_callback = |message: Payload, socket: Client| {
        async move {
            match message {
                Payload::Text(values, _) => println!("{:#?}", values),
                Payload::Binary(bytes, _) => println!("Received bytes: {:#?}", bytes),
                // This is deprecated use Payload::Text instead
                #[allow(deprecated)]
                Payload::String(str, _) => println!("{}", str),
            }
        }.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));
}

Trait Implementations§

Source§

impl Clone for Client

Source§

fn clone(&self) -> Client

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

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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
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