Comments (3)
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.
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.
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)
- Add EngineIo v3 support HOT 13
- SocketIO: Lots of panics on unwrap in case of there are lots of clients HOT 5
- Benchmark and replace Rwlock Hashmap HOT 6
- Socket ID collision solution HOT 1
- Run on dedicated path HOT 2
- Set up code formatting HOT 2
- Splitting the `Error` enum in `engineioxide` into smaller enums
- Document commit message conventions/guidelines
- How to specific transports? HOT 1
- Add SocketIO v4 support
- Vacations: I'm completly out from the 5th of july until the 24th. HOT 2
- Missing Content-Type on response HOT 2
- How join a socket to room and emitting to room? HOT 1
- Unknown panic HOT 2
- Can I use it for production? HOT 3
- Is there any middleware support where I can check if authentication is ok before the "connection" event fires on the socket? HOT 3
- How do we access a namespace and get all/specific sockets in it? HOT 1
- Tracking issue: hyper v1.0 support
- Add support for surrealdb HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from socketioxide.