I
I
Ivan Ivanovich2021-12-08 09:10:25
Node.js
Ivan Ivanovich, 2021-12-08 09:10:25

How to implement global event in Socket.IO version 4?

Good day.

There is a task to create a global event in Socket.IO on the server side and be able to trigger it. Also from the server side.

I looked at the solution in the screencast from Ilya Kantor.

I couldn't determine the version of the Socket.IO package, but the solution looks very simple:

module.exports = function(server) {
  var io = require('socket.io').listen(server);
  // other code

  // global event
  io.sockets.on('session:reload', function(sid) {
    // code
  });
}


And here's how it triggers this global event (session:reload): Socket.IO 4 does not have the $emit function at all. I tried:
io.sockets.$emit("session:reload", sid);


io.on('GlobalEvent', (greetings) => {
  console.log(`Got socket with greetings ${greetings}`);
});

setTimeout(() => {
  io.emit('GlobalEvent', 'Hello from GlobalEvent!');
  console.log('setTimeout emit sent');
}, 500);


So:
io.sockets.on('GlobalEvent', (greetings) => {
  console.log(`Got socket with greetings ${greetings}`);
});

setTimeout(() => {
  io.sockets.emit('GlobalEvent', 'Hello from GlobalEvent!');
  console.log('setTimeout emit sent');
}, 500);


But he still couldn't get the result. Console log in setTimeout works, but Sockets don't catch it.

If someone knows the solution to this issue, please write it. Thanks in advance

UPD : I found the serverSideEmit event but its implementation in the package is quite interesting:
61b04c37dd6ae476023779.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Ivanovich, 2021-12-10
@IwanQ

io.engine.on('globalEvent', () => {
  // handler
});

// trigger
io.engine.emit('globalEvent', 'some data');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question