Quick start
Connect
use std::time::Duration;
use serde_json::json;
use socketio_next::{Client, ClientBuilder, ConnectionState, Event};
#[tokio::main]
async fn main() -> socketio_next::Result<()> {
let client = ClientBuilder::new("http://localhost:3000")
.auth(json!({ "token": "abc" }))
.on("chat", |event: Event, _client: Client| async move {
println!("chat: {:?}", event.payload());
})
.on_state_change(|state: ConnectionState, _client: Client| async move {
println!("{state:?}");
})
.connect()
.await?;
client.emit("chat", "hello")?;
let reply = client
.emit_with_ack("add", vec![json!(1), json!(2)], Duration::from_secs(5))
.await?;
println!("1 + 2 = {}", reply.arg::<i64>(0)?);
client.disconnect().await
}
connect() resolves once the server answered the namespace CONNECT. It fails with the error of that first attempt (a refused auth is ConnectRejected, an unreachable server ConnectTimeout or an engine error); reconnection starts only after a connection existed.
The URL's path is the namespace, like io("http://host/admin") in JavaScript: ClientBuilder::new("http://localhost:3000/admin") joins /admin. The engine.io path is .path(..) (default /socket.io/).
A server to try it
import { Server } from 'socket.io'
const io = new Server(3000)
io.on('connection', (socket) => {
socket.on('chat', (text) => io.emit('chat', text))
socket.on('add', (a, b, ack) => ack(a + b))
})
Handlers
A handler gets the Event and a Client. Write it as a closure returning a future (runs on the client's event task) or as a plain closure (runs on tokio's blocking pool and may block). Handlers run one at a time, in arrival order, and may emit, await acks and add handlers.
client.on("question", |event: Event, _: Client| {
let (text, n): (String, u32) = event.payload().deserialize().unwrap();
event.ack(json!({ "answer": n + 1 })).unwrap(); // answers the server's callback
});
Emit
emit never blocks: it queues the packet and returns. While disconnected it fails with Error::NotConnected (or queues, with buffer_while_disconnected). emit_with_ack(..).await returns the ack's arguments, or AckTimeout / Disconnected.
State
use socketio_next::ConnectionState;
if client.connected() {
println!("socket id {:?}", client.id());
}
let state = client.wait_for(|s| matches!(s, ConnectionState::Connected { .. })).await;
See Connection state for the states, reasons and link_info().
Examples
The repository has runnable examples in examples/src/bin: basic, auth, reconnect, binary, transports, blocking. Start the test servers and run one:
just servers-setup && just servers
just example basic