据我所知,一旦我创建了一个套接字,我就可以创建一个数组来存储它
userArray[socket.nickname]=socket;
然后我可以向它发送一条消息:
io.sockets.socket(userArray[data.to]).emit('private message', tstamp(), socket.nickname, message);
基本逻辑是将每个套接字的副本存储在由昵称标识的对象中。当我想向该套接字发送消息时,我使用套接字的副本,并通过 io.sockets.socket(id).emit() 发送消息。整个服务器代码如下:
io.sockets.on('connection', function (socket) {
socket.on('user message', function (msg) {
socket.broadcast.emit('user message', tstamp(), socket.nickname, msg);
updateLog('user message', socket.nickname, msg);
});
socket.on('private message', function(data) {
socket.get(data.nickname, function (err, name) {
console.log('Chat message by ', name);
});
updateLog('private message', socket.nickname, data.message);
message=data.message;
io.sockets.socket(userArray[data.to]).emit('private message', tstamp(), socket.nickname, message);
});
socket.on('get log', function () {
updateLog(); // Ensure old entries are cleared out before sending it.
io.sockets.emit('chat log', log);
});
socket.on('nickname', function (nick, fn) {
var i = 1;
var orignick = nick;
while (nicknames[nick]) {
nick = orignick+i;
i++;
}
fn(nick);
nicknames[nick] = socket.nickname = nick;
userArray[socket.nickname]=socket;
socket.set('nickname', nick, function () { socket.emit('ready'); });
socket.broadcast.emit('announcement', nick + ' connected');
// io.sockets.socket(userArray[nick]).emit('newID', 'Your name is: ' + nick, '. Your ID is: '+ userArray[nick]);
io.sockets.emit('nicknames', nicknames);
});