【发布时间】:2013-08-14 22:57:12
【问题描述】:
我已经实现了 Node.js 服务器端和 ios 客户端来发送 pm 消息。但主要问题是,我的代码仍然像文本消息一样为所有客户端广播。 (我在 3 部手机上试过,我只是向特定的客户发送电子邮件,但客户和我发送该消息的手机都没有消息)
我的服务器代码如下所示:
io.sockets.on('connection', function (socket) {
var userName;
var userSrcID;
socket.on('setUserName',function(user){
userName = user.name;
userSrcID = user.id;
clients[user.name] = socket;
clients[user.id] = socket;
console.log('data = ',user);
//io.sockets.emit('new user', user.name + " has joined.");
});
socket.on('message', function(msg){
io.sockets.emit('message', msg);
});
socket.on('pm', function(msg){
fromMsg = {from:userSrcID, txt:msg}
//clients[msg.to].emit('private message', fromMsg);
console.log('Gidicek username:',userName);
io.sockets.emit('new message',{msg: msg,destID:userSrcID});
我可以建立一个条件,如果该消息的目标用户 ID 不属于我的用户 ID,请不要显示,但它更像是使用 Old-School HUB 网络而不是 switch :)
任何帮助将不胜感激
最好的问候,
【问题讨论】:
-
如果你想发送给特定的用户,你只需要发送到那个用户的套接字。见:Send message to specific client with socket.io and node.js中的第二个答案
-
我将客户端推送到节点的用户标识作为目标标识,即 = clients[user.id] = socket;那么如何使用该声明发送该用户?
-
clients[userDestId].emit(…)