Struct my_rust_socketio::asynchronous::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
impl Client
sourcepub async fn emit<E, D>(&self, event: E, data: D) -> Result<(), Error>where
E: Into<Event>,
D: Into<Payload>,
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 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());
}
sourcepub async fn disconnect(&self) -> Result<(), Error>
pub async fn disconnect(&self) -> Result<(), Error>
Disconnects this client from the server by sending a socket.io
closing
packet.
Example
use 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;
}
sourcepub 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>,
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 alloc
s 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 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::String(str) => println!("{}", str),
Payload::Binary(bytes) => println!("Received bytes: {:#?}", bytes),
}
}.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));
}