Module message

Module message 

Source
Expand description

MessageHandler trait and implementations, used to handle the message events. It has a flexible axum-like API, you can put any arguments as long as it implements the FromMessageParts trait or the FromMessage trait for the last argument.

All the types that implement FromMessageParts also implement FromMessage.

You can also implement the FromMessageParts and FromMessage traits for your own types. See the extract module doc for more details on available extractors.

Handlers must be async.

§Example with async closures

let (svc, io) = SocketIo::new_svc();
io.ns("/", async |s: SocketRef| {
    s.on("event", async |s: SocketRef, Data::<String>(data)| {
       tokio::time::sleep(std::time::Duration::from_secs(1)).await;
       println!("Socket received event with data: {}", data);
    });
    // `Bin` extractor must be the last argument because it consumes the rest of the packet
    s.on("/binary_event", async |s: SocketRef, TryData::<String>(data)| {
      println!("Socket received event with data: {:?}", data);
    })
});

§Example with an async non-anonymous handler

// async named event handler
async fn on_event(s: SocketRef, Data(data): Data<serde_json::Value>, ack: AckSender) {
    tokio::time::sleep(std::time::Duration::from_secs(1)).await;
    ack.send("Here is my acknowledgment!").ok();
}
let (svc, io) = SocketIo::new_svc();
io.ns("/", async |s: SocketRef| {
    s.on("event", on_event);
    // It is also possible to reuse handlers, like this:
    s.on("event_2", on_event);
});

Traits§

FromMessage
A trait used to extract and consume arguments from the message event. The Result associated type is used to return an error if the extraction fails, in this case the handler is not called.
FromMessageParts
A trait used to extract arguments from the message event. The Result associated type is used to return an error if the extraction fails, in this case the handler is not called.
MessageHandler
Define a handler for the connect event. It is implemented for closures with up to 16 arguments. They must implement the FromMessageParts trait or the FromMessage trait for the last one.