Totodore / socketioxide

A socket.io server implementation in Rust that integrates with the Tower ecosystem and the Tokio stack.
https://docs.rs/socketioxide
MIT License
1.13k stars 49 forks source link

`on_disconnection` cannot accept non anonymous functions #322

Closed hlf20010508 closed 1 month ago

hlf20010508 commented 1 month ago

Describe the bug on_disconnection can accept closures but not non anonymous functions.

The function is called disconnect. The error is

the trait bound `for<'a> fn(&'a socketioxide::extract::SocketRef) {disconnect}: DisconnectHandler<LocalAdapter, _>` is not satisfied
the trait `DisconnectHandler<LocalAdapter, _>` is not implemented for fn item `fn(&SocketRef) {disconnect}`

To Reproduce

pub fn disconnect(socket: &SocketRef) {}

let (socketio_layer, socketio) = SocketIo::new_layer();

socketio.ns(
    "/",
    |socket: SocketRef| {
        // socket.on_disconnect(|socket: SocketRef| {}); // this works
        socket.on_disconnect(disconnect); // this not
    },
);

Expected behavior The example in doc says

async fn handler(s: SocketRef, reason: DisconnectReason) {
    tokio::time::sleep(std::time::Duration::from_secs(1)).await;
    println!("Socket disconnected on {} namespace with id and reason: {} {}", s.ns(), s.id, reason);
}

let (svc, io) = SocketIo::new_svc();

// You can reuse the same handler for multiple sockets
io.ns("/", |s: SocketRef| {
    s.on_disconnect(handler);
});
io.ns("/admin", |s: SocketRef| {
    s.on_disconnect(handler);
});

But actually this doesn't work.

Versions (please complete the following information):

Additional context I don't know if there's something that I missed.

Totodore commented 1 month ago

You are taking SocketRef by ref whereas you should take it by value:

pub fn disconnect(socket: &SocketRef) {} Vs pub fn disconnect(socket: SocketRef) {}

hlf20010508 commented 1 month ago

It works. Thanks for your help.

hlf20010508 commented 1 month ago

By the way, you missed code block end "```" here. https://github.com/Totodore/socketioxide/blob/9415e058ecd6aa509f6199f35d0097ee81768e14/socketioxide/src/socket.rs#L259