栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

您的代码存在一些问题,首先是您不应该通过Socket.IO对用户进行身份验证,您应该确保用户只有在经过身份验证后才能进行连接。如果您使用的是Express,则以下文章可以为您提供很多帮助:http : //www.danielbaulig.de/socket-
ioexpress/

另外,您应该避免像这样发送消息,因为它在内部是Socket.IO的一部分,并且可能会更改:

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

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

// the clients hash stores the sockets// the users hash stores the username of the connected user and its socket.idio.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内部的一部分,因此可以随时对其进行更改,因此上面的解决方案更加“安全”。

您可能希望在客户端代码中更改的另一件事是

var socket = io.connect('');
with
var socket =io.connect('http://localhost');
,正如我们在Socket.IO的官方示例中看到的那样:http ://socket.io/#how-to-use



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/446451.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号