我在向特定客户端发送私人消息时遇到问题。 这个事件"对话私人帖子"没有工作,我的客户从未看到这些私人信息。
我不知道出了什么问题。
这是我的代码:
server.js
io.on('connection', function (socket, username) {
console.log('New client connected (id=' + socket.id + ').');
socket.on('subscribe', function(room) {
console.log('joining room', room);
socket.join(room);
});
socket.on('send message', function(data) {
console.log('sending room post', data.room);
socket.to(data.room).emit('conversation private post', {
message: data.message
});
});
});
client.js
<html>
<head>
<title>Getting started with Sockets</title>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script>
var conversation_id = Math.floor(Math.random() * 1000 )
var socket = io('http://localhost:3000');
socket.emit('subscribe', conversation_id);
socket.emit('send message', {
room: conversation_id,
message: "Some message"
});
socket.on('conversation private post', function(data) {
console.log("Private conversation", data)
});
</script>
</head>
<body>
<div id="serverMsg">Waiting for the message from server:</div>
</body>
</html>
答案 0 :(得分:0)
在客户端上,使用以下数据向服务器发出一个对象:
{
to: [the other receiver's username as a string] ,
from: [the person who sent the message as string] ,
message: [the message to be sent as string]
}
在服务器上,侦听消息。收到消息后,将数据发送给接收方。
"the user you want to send"[data.to].emit('receivedMessage', data)