使用Node.js和Socket.io发送私人消息(Send private message using Node.js and Socket.io)

我正在使用node.js和socket.io实现一个小型聊天应用程序。 一切都很顺利,直到我尝试发送私人消息。 以下是服务器的代码:

... var to = users[name]; socket.to(to).emit('private message', {userName: socket.username, message: msg} ); ...

客户端代码:

... socket.on('private message', function(data){ alert(data.message); }); ...

我的问题是,在客户端事件永远不会被解雇,任何人都可以帮我解决这个问题吗? 谢谢。

I am implementing a small chat application using node.js and socket.io. Everything goes well till I try to send a private message. Here is the code for the server:

... var to = users[name]; socket.to(to).emit('private message', {userName: socket.username, message: msg} ); ...

Code on the client side:

... socket.on('private message', function(data){ alert(data.message); }); ...

My problem is that on the client side the event is never fired, can anyone help me to fix this issue? Thank you.

最满意答案

也许现在回答太迟了..

您可以使用socket.id发送私人消息或私下发送数据。

io.on('connect', function(){ io.to(socket.id).emit('send message', 'test'); });

Maybe this is too late to answer..

You can use socket.id to send private message or send data privately.

io.on('connect', function(){ io.to(socket.id).emit('send message', 'test'); });

更多推荐