我正在尝试向单个客户端发出通知,但发射似乎根本没有触发,而broadcast.emit工作正常。但问题是广播是通知所有客户,即使我提供socket.id。
任何人都知道我做错了什么?
var app = express( );
var querystring = require('querystring');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var clients = {};
io.sockets.on('connection', function( socket ) {
socket.on( 'subscribe', function( userID ) {
clients[userID] = socket.id;
});
socket.on( 'notifyMsg', function( data ) {
var obj = JSON.parse( data );
for( var i=0; i<obj.info.notifyUserIDs.length; i++ ) {
var to = clients[obj.info.notifyUserIDs[i]];
if( to ) {
// Doesn't work
io.sockets.socket(to).emit( 'notification', data );
// Works
//io.sockets.socket(to).broadcast.emit( 'notification', data );
}
}
});
});
答案 0 :(得分:0)
您如何考虑将套接字本身存储在客户端哈希中并像这样使用它?
var app = express( );
var querystring = require('querystring');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var clients = {};
io.sockets.on('connection', function( socket ) {
socket.on( 'subscribe', function( userID ) {
clients[userID] = socket;
});
socket.on( 'notifyMsg', function( data ) {
var obj = JSON.parse( data );
for( var i=0; i<obj.info.notifyUserIDs.length; i++ ) {
var to = clients[obj.info.notifyUserIDs[i]];
if( to ) {
to.emit( 'notification', data );
}
}
});
});