[英]Send messages from server to client socket.io
我正在嘗試使用socket.io將消息從NodeJS服務器發送到客戶端
但是,我在整個互聯網上都發現了相同的做法,即使用io.on('connection',handler)包裝發射,然后使服務器偵聽特殊的“ channel”事件,如下所示:
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;
我的問題是:我想在連接包裝器之外發出消息,例如從我的路線或其他腳本發出消息。 可能嗎?
謝謝。
是。 您只需要保留對套接字的引用。
// 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);
});
然后在代碼中的其他地方...
sockets[0].emit('someEvent');
我通常要做的是為新客戶端分配一個UUID,並將其添加到以此UUID為鍵的對象中。 這對於日志記錄非常有用,而對於日志記錄也不太方便,因此我到處都保持一致的ID。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.