通过 socket.id 向客户端发送消息 [英] Sending a message to a client via its socket.id

查看:37
本文介绍了通过 socket.id 向客户端发送消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户的套接字 ID 直接存储在 io.sockets.on('connect') 函数中时,我似乎只能向用户发送消息.我不知道为什么在他们登录后尝试存储他们的套接字 ID 时它不起作用.

I can only seem emit messages to users when their socket id has been directly stored within the io.sockets.on('connect') function. I don't know why it doesn't work when trying to store their socket id after they have logged in.

工作:

  var clients = {};
  /** A new socket connection has been accepted */
  io.sockets.on('connection', function (socket)
  {
    //Used to access session id
    var hs = socket.handshake;            
        clients[socket.id] = socket; // add the client data to the hash   
        users['brownj2'] = socket.id; // connected user with its socket.id

    socket.on('user-login', function(user){
      if(!users[username]){
        //users[username] = socket.id; // connected user with its socket.id
      }
    })

    socket.on('page-load', function(pid)
    {
      if(users['brownj2'])
      {        
        clients[users['brownj2']].emit('hello');
      }
      else
      {
        console.log("NOT FOUND BROWNJ2");
      }
    }
  }

不工作:

  var clients = {};
  /** A new socket connection has been accepted */
  io.sockets.on('connection', function (socket)
  {
    //Used to access session id
    var hs = socket.handshake;            
        clients[socket.id] = socket; // add the client data to the hash            

    socket.on('user-login', function(user){          
      if(!users['brownj2']){
        users['brownj2'] = socket.id; // connected user with its socket.id
      }
    })

    socket.on('page-load', function(pid)
    {
      if(users['brownj2'])
      {        
        clients[users['brownj2']].emit('hello');
      }
      else
      {
        console.log("NOT FOUND BROWNJ2");
      }
    }
  }

JavaScript 客户端代码片段

var socket = io.connect('');
socket.on("hello", function(){
  alert("Hi Jack");
  console.log("WEBSOCKET RECIEVED");
})

解决方案:感谢@alessioalex我不得不从登录页面中删除对 socket.io 的引用,并将以下内容添加到 io.sockets.on('connection')

Solution: Thanks @alessioalex I have had to remove the reference to socket.io from the login page, and add the following into io.sockets.on('connection')

var hs = socket.handshake;

sessionStore.get(hs.sessionID, function(err, session){
  console.log("SESSION: " + util.inspect(session));

  clients[socket.id] = socket; // add the client data to the hash
  validUsers[session.username] = socket.id; // connected user with its socket.id
})

推荐答案

你的代码有一些问题,首先你不应该通过 Socket.IO 对用户进行身份验证,你应该确保他们只有在身份验证后才能连接.如果您使用的是 Express,那么下面的文章可以帮到您很多:http://www.danilbaulig.de/socket-ioexpress/

There are some problems with your code, the first being you shouldn't authenticate users through Socket.IO, you should make sure they can connect only after they authenticated. If you are using Express, then the following article can help you a lot: http://www.danielbaulig.de/socket-ioexpress/

你也应该避免发送这样的消息,因为它是 Socket.IO 内部的一部分并且可能会改变:

Also you should be avoiding sending messages like so, since that is part of Socket.IO internally and may change:

io.sockets.socket(id).emit('hello');

相反(如果您想向特定客户端发送消息)最好保留一个对象,例如与连接的客户端(并在断开连接后删除客户端):

Instead (if you want to send a message to a specific client) it's better to keep an object for example with the connected clients (and remove the client once disconnected):

// the clients hash stores the sockets
// the users hash stores the username of the connected user and its socket.id
io.sockets.on('connection', function (socket) {
  // get the handshake and the session object
  var hs = socket.handshake;
  users[hs.session.username] = socket.id; // connected user with its socket.id
  clients[socket.id] = socket; // add the client data to the hash
  ...
  socket.on('disconnect', function () {
    delete clients[socket.id]; // remove the client from the array
    delete users[hs.session.username]; // remove connected user & socket.id
  });
}

// we want at some point to send a message to user 'alex'
if (users['alex']) {
  // we get the socket.id for the user alex
  // and with that we can sent him a message using his socket (stored in clients)
  clients[users['alex']].emit("Hello Alex, how've you been");
}

当然,io.sockets.socket(id) 可以工作(没有实际测试),但它也可以随时更改,因为它是 Socket.IO 内部的一部分,所以我的解决方案上面更安全".

Sure, io.sockets.socket(id) may work (didn't actually test), but also it can be always changed as it's part of the Socket.IO internals, so my solution above is more 'safe'.

您可能希望在客户端更改代码的另一件事是 var socket = io.connect('');var socket = io.connect('http://localhost');,正如我们在 Socket.IO 官方示例中看到的:http://socket.io/#how-to-use

Another thing you may want to change in your code on the client side is var socket = io.connect(''); with var socket = io.connect('http://localhost');, as we can see in the official example of Socket.IO here: http://socket.io/#how-to-use

这篇关于通过 socket.id 向客户端发送消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆