简体   繁体   中英

Send messages from server to client socket.io

I am trying to send a message from NodeJS server to client using socket.io

However, I found the same practice all over the internet, which is wrapping the emit with io.on('connection', handler) and then making the server listen on a special "channel" event like so:

var io = require('socket.io')();

var socketioJwt = require('socketio-jwt');
var jwtSecret = require('./settings').jwtSecret;

var User = require('./models/users').User;

io.set('authorization', socketioJwt.authorize({
  secret: jwtSecret,
  handshake: true
}));

var sockets = [];

io.on('connection', function(socket) {
    sockets.push(socket);
});

sendLiveUpdates = function(gameSession) {
    console.log(sockets);
}

exports.sendLiveUpdates = sendLiveUpdates;

exports.io = io;

My problem is: I want to emit messages outside this on connection wrapper, example from my routes or other scripts. Is it possible?

Thanks.

Yes. You just need to keep a reference to the socket.

// Just an array for sockets... use whatever method you want to reference them
var sockets = [];

io.on('connection', function(socket) {
  socket.on('event', function() {
    io.emit('another_event', message);
  });

  // Add the new socket to the array, for messing with later
  sockets.push(socket);
});

Then somewhere else in your code...

sockets[0].emit('someEvent');

What I usually do is assign new clients a UUID and add them to an object keyed by this UUID. This comes in handy for logging and what not as well, so I keep a consistent ID everywhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM