gpt4 book ai didi

javascript - Socket.io 发射不起作用,但广播正常

转载 作者:行者123 更新时间:2023-11-28 08:44:33 25 4
gpt4 key购买 nike

我试图向单个客户端发出通知,但发出似乎根本没有触发,而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 );
}
}
});
});

最佳答案

您对将套接字本身存储在客户端哈希中并像这样使用它有何看法?

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 );
}
}
});
});

关于javascript - Socket.io 发射不起作用,但广播正常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20030946/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com