0

据我所知,一旦我创建了一个套接字,我就可以创建一个数组来存储它

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

1 回答 1

1

目前尚不清楚您的实际问题是什么,但是如果您已将套接字对象存储为对象键的值(这就是您正在做的;这userArray是一个很容易引起误解的名称,因为它不是数组),那么您只需调用方法关于价值。IOW,而不是

io.sockets.socket(userArray[data.to]).emit(...

你只需写:

userArray[data.to].emit(...
于 2012-07-11T03:10:48.020 回答