Answer the question
In order to leave comments, you need to log in
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
});
}
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);
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);
Answer the question
In order to leave comments, you need to log in
io.engine.on('globalEvent', () => {
// handler
});
// trigger
io.engine.emit('globalEvent', 'some data');
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question