Module socketioxide::handler::connect
source · Expand description
ConnectHandler trait and implementations, used to handle the connect event.
It has a flexible axum-like API, you can put any arguments as long as it implements the FromConnectParts trait.
You can also implement the FromConnectParts trait for your own types.
See the extract module doc for more details on available extractors.
Handlers can be optionally async.
Example with sync closures
let (svc, io) = SocketIo::new_svc();
// Here the handler is sync,
// if there is a serialization error, the handler is not called
io.ns("/nsp", move |s: SocketRef, Data(auth): Data<String>| {
println!("Socket connected on /nsp namespace with id: {} and data: {}", s.id, auth);
});Example with async closures
let (svc, io) = SocketIo::new_svc();
// Here the handler is async and extract the current socket and the auth payload
io.ns("/", move |s: SocketRef, TryData(auth): TryData<String>| async move {
println!("Socket connected on / namespace with id and auth data: {} {:?}", s.id, auth);
});
// Here the handler is async and only extract the current socket.
// The auth payload won't be deserialized and will be dropped
io.ns("/async_nsp", move |s: SocketRef| async move {
println!("Socket connected on /async_nsp namespace with id: {}", s.id);
});Example with async non anonymous functions
async fn handler(s: SocketRef, TryData(auth): TryData<String>) {
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
println!("Socket connected on {} namespace with id and auth data: {} {:?}", s.ns(), s.id, auth);
}
let (svc, io) = SocketIo::new_svc();
// You can reuse the same handler for multiple namespaces
io.ns("/", handler);
io.ns("/admin", handler);Traits
- Define a handler for the connect event. It is implemented for closures with up to 16 arguments. They must implement the
FromConnectPartstrait. - A trait used to extract the arguments from the connect event. The
Resultassociated type is used to return an error if the extraction fails, in this case theConnectHandleris not called.