Reputation: 3031
I used
const my_socket = io.sockets.connected['YnwlYH-gCKT2K9jEAAAu'];
a lot.
https://stackoverflow.com/a/24464450/1707015
Is it broken in 3.X and 4.0.1?
$ npm list socket.io
[email protected]
$ npm list socket.io-client
[email protected]
# Object.keys(io.sockets):
_events,_eventsCount,_maxListeners,sockets,_fns,_ids,server,name,adapter
# io.sockets.connected:
undefined
# io.sockets.connected['YnwlYH-gCKT2K9jEAAAu']:
TypeError: Cannot read property 'YnwlYH-gCKT2K9jEAAAu' of undefined
at Socket.<anonymous> (/path:row:char)
at processTicksAndRejections (internal/process/task_queues.js:86:5)
I can get it run with version 2 (instead of 3 or 4):
$ npm install --quiet --save-dev [email protected] [email protected]
Yes, this is literally an X
- for the newest sub version.
Do you have any refactoring instructions?
Upvotes: 12
Views: 12493
Reputation: 621
For any adapter, you can use fetchSockets() function to get the socket connection by socketId.
const socketList = await io.in(socketId).fetchSockets();
Instead of socketId, you can use socketRoom as well.
Refer here for the documentation.
Upvotes: 1
Reputation: 1
"socket.io": "^4.1.3"
nsp.sockets.get(socketid).join(roomId)
nsp.to(roomId).emit("message",{message : "something"})
it worked for me
Upvotes: -1
Reputation: 3031
This question and answer is probably a (newer/better) duplicate of https://stackoverflow.com/a/66835961/1707015. Sorry, I only saw it now. Credits to Sanjay Nishad.
const my_socket = io.sockets.sockets.get('YnwlYH-gCKT2K9jEAAAu');
Upvotes: 33