11

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
socket.io@4.0.1

$ npm list socket.io-client
socket.io-client@4.0.1
# 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 socket.io@2.X socket.io-client@2.X

Yes, this is literally an X - for the newest sub version.

Do you have any refactoring instructions?

qräbnö
  • 2,722
  • 27
  • 40

2 Answers2

27

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');
qräbnö
  • 2,722
  • 27
  • 40
  • 1
    For context, this is documented here: https://socket.io/docs/v4/server-api/#namespacesockets Where it says that `namespace.sockets` is of type `Map` So to explain the above: `io.sockets` is the default namespace `defeaultNamespace.sockets` is a Map where a Map has a method called `get()` that happens to return an object of type `Socket` – Ben Zenker May 03 '22 at 18:37
  • 1
    How does this work with adapter? Does `io.sockets.sockets` contains all sockets from across the adapter, e.g. Redis? – boozi Feb 22 '23 at 12:56
-1

"socket.io": "^4.1.3"

nsp.sockets.get(socketid).join(roomId)
nsp.to(roomId).emit("message",{message : "something"})

it worked for me

HuyNguyen
  • 1
  • 1