Events and acks
Handlers
A handler gets an Event (name, Payload, ack) and the Client. Write it as:
- a closure returning a future: runs on the client's event task;
- a plain closure: runs on tokio's blocking pool and may block.
No boxing is needed. Handlers run one at a time, in arrival order, on one event task for the client's whole life. A handler may emit, await acks, add handlers and call disconnect() without deadlocks (no event handler starts after it; the Closed state still reaches on_state_change). A panicking handler, even one that panics before it returns its future, is contained and does not stop the client.
A handler that keeps a Client of its own (captured in the closure) keeps the client alive for good, since the client owns its handlers. Capture a WeakClient instead:
let weak = client.downgrade();
client.on("ping", move |_: Event, _: Client| {
if let Some(client) = weak.upgrade() {
let _ = client.emit("pong", ());
}
});
use serde_json::json;
use socketio_next::{Client, Event};
client.on("question", |event: Event, _: Client| {
let (text, n): (String, u32) = event.payload().deserialize().unwrap();
event.ack(json!({ "answer": n + 1 })).unwrap(); // the server's callback
});
client.once("ready", |_: Event, _: Client| println!("ready"));
let id = client.on_any(|event: Event, _: Client| println!("{}", event.name()));
client.off_listener(id);
| Method | What |
|---|---|
on(event, handler) | handles event; returns a ListenerId |
once(event, handler) | handles the next event only |
on_any(handler) | every event, before the event's own handlers (onAny) |
on_state_change(handler) | every ConnectionState transition, in order with the events |
off(event) | removes the event's handlers; returns how many |
off_any() | removes the on_any handlers |
off_listener(id) | removes one handler |
listener_count(event) | handlers of event |
Handlers are matched by exact event name. Events with no handler are dropped (on_any sees them).
The event
Event method | What |
|---|---|
name() | the event name |
payload() / into_payload() | the arguments as a Payload |
arg::<T>(i) | argument i deserialized |
wants_ack() | the server passed a callback |
ack(data) | answers the callback; sent at most once, later calls are ignored |
ack_sender() | an AckSender to answer later, from another task |
Emit
client.emit("chat", "hello")?; // one string argument
client.emit("move", vec![json!(1), json!(2)])?; // two arguments
client.emit("ping", ())?; // no arguments
client.emit("user", Payload::serialize(&user)?)?; // any Serialize
emit never blocks: it queues the packet for the connection task and returns. Offline it fails with Error::NotConnected, or queues with buffer_while_disconnected. Reserved names (connect, connect_error, disconnect, ...) fail with ReservedEvent.
data is anything Into<Payload>: a serde_json::Value, a Vec<Value> (several arguments), a string, a number, () (no arguments), Bytes / Vec<u8>, or Payload::serialize(&your_struct)?.
Acks from the server
use std::time::Duration;
let reply = client
.emit_with_ack("add", vec![json!(1), json!(2)], Duration::from_secs(5))
.await?;
let sum: i64 = reply.arg(0)?;
emit_with_ack(event, data, timeout).await returns the ack's arguments as a Payload, or fails with AckTimeout when no answer came in time, Disconnected when the connection was lost first. Ack ids are unique per client.
Acks to the server
When the server emits with a callback (socket.emit("question", "?", (answer) => ...)), event.wants_ack() is true and event.ack(data) answers it, as ACK or BINARY_ACK. event.ack_sender() returns a handle to answer later.
Payload
pub enum Payload {
Text(Vec<Value>), // JSON arguments
Binary(Bytes), // one lone buffer
Mixed { args: Vec<Value>, attachments: Vec<Bytes> },
}
payload.args(), payload.binary(), payload.arg::<T>(i), payload.deserialize::<T>() (all arguments as a tuple or struct), len(), is_empty().
Binary
A lone buffer arrives as Payload::Binary. Buffers anywhere else (several, next to JSON, inside objects) arrive as Payload::Mixed { args, attachments }, where {"_placeholder":true,"num":n} in args stands for attachments[n]: the socket.io wire format. Send the same shapes; Payload::placeholder(n) builds a placeholder.
use bytes::Bytes;
use socketio_next::Payload;
client.emit("upload", Payload::Mixed {
args: vec![json!({ "name": "a.bin", "data": Payload::placeholder(0) })],
attachments: vec![Bytes::from_static(b"\x00\x01\x02")],
})?;