Code Monkey home page Code Monkey logo

Comments (3)

cr1tbit avatar cr1tbit commented on May 27, 2024 1

Thanks for the extremely fast response :)

I achieved the thing I wanted, with your advice of using static hashmap. While not very elegant, it seems to be working for now. I'll update my code once we'll get that io struct you're talking about.

let debug_timer = every(5).seconds()
    .perform(|| async {
        //perform dead socket garbage collection
        SOCKS.write().unwrap().retain(|_, v| v.upgrade().is_some());
            
        for (k,v) in SOCKS.read().unwrap().iter() {
            if let Some(socket) = v.upgrade() {
                println!("send to socket {}", socket.sid);
                socket.emit("log", format!("timer for {}", socket.sid)).ok();
            } else {
                println!("socket {} is dead",k);
            }
        }
    });
spawn(debug_timer);

Have a nice evening.

from socketioxide.

Totodore avatar Totodore commented on May 27, 2024

Hi !

The best way would be to have a cheaply clonable io struct that you could use to retrieve any socket/rooms. Currently it is not available. So the best way to do what you want is to build a shared DashMap or Mutex<HashMap> with an id as a key and the socket value. Thanks to that you would be able to have a socket ref everywhere :

#[derive(Deserialize)]
struct Auth {
    pub mqtt_id: String,
}
use once_cell::sync::Lazy;

static SOCKS: Lazy<RwLock<HashMap<String, Weak<Socket<LocalAdapter>>>>> =
    Lazy::new(|| RwLock::new(HashMap::new()));

pub async fn handler(socket: Arc<Socket<LocalAdapter>>) {
    info!("Socket connected on / with id: {}", socket.sid);
    if let Ok(data) = socket.handshake.data::<Auth>() {
        info!("mqtt id: {:?}", &data.mqtt_id);
        SOCKS
            .write()
            .unwrap()
            .insert(data.mqtt_id, Arc::downgrade(&socket.clone()));
    } else {
        info!("No mqtt_id provided, disconnecting...");
        socket.disconnect().ok();
        return;
    }

Because the socket parameter is an Arc<Socket> you can clone it everywhere you want. However, there is currently one major drawback of doing that. If you keep the socket ref in your hashmap even when the socket is disconnected there will be a memory leak. And there is currently no on_disconnect handler so you can't remove the ref when the socket is disconnected (it is going to be available soon though).

So the only solution is to downgrade the Arc reference to a Weak reference in your hashmap so that when the socket is disconnected, the reference you own will allow the socket to be dropped.

I'll add another answer when the features needed for this kind of issue will be released.

from socketioxide.

Totodore avatar Totodore commented on May 27, 2024

Hey !

In the new version (v0.5.0) you have an on_disconnect handler so you don't have to hold a Weak reference, you can only set the on_disconnect handler and remove the socket ref in your hashmap at that moment.

#[derive(Deserialize)]
struct Auth {
    pub mqtt_id: String,
}
use once_cell::sync::Lazy;

static SOCKS: Lazy<RwLock<HashMap<String, Arc<Socket<LocalAdapter>>>>> =
    Lazy::new(|| RwLock::new(HashMap::new()));

pub async fn handler(socket: Arc<Socket<LocalAdapter>>) {
    info!("Socket connected on / with id: {}", socket.sid);
    if let Ok(data) = socket.handshake.data::<Auth>() {
        info!("mqtt id: {:?}", &data.mqtt_id);
        SOCKS
            .write()
            .unwrap()
            .insert(data.mqtt_id, socket.clone());
    } else {
        info!("No mqtt_id provided, disconnecting...");
        socket.disconnect().ok();
        return;
    }

    socket.on_disconnect(|socket, reason| {
        info!("socket disconnected, reason: {reason}");
        SOCKS.write().unwrap().remove(socket.sid);
    })
}

from socketioxide.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.