且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过socket.id向客户端发送消息

更新时间:2022-04-18 21:26:29

您的代码存在一些问题,第一个是你不应该通过Socket.IO对用户进行身份验证,你应该确保他们只有在经过身份验证后才能连接。如果您使用的是Express,那么下面的文章可以为您提供很多帮助: http://www.danielbaulig。 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(''); with 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