我正在用socket.io设置Web套接字服务器,看来消息至少发送了两次。有时甚至会闹翻。 (很少甚至超过4次),但永远不会发送一次。我应该如何设置我的处理程序或客户代码,以便每时每刻都收到一条消息?
我的客户很快,而我的服务器在node.js中。我在服务器本身上运行Ubuntu 16.04。
Node.js:
// Here is an array of all connections to the server
var connections = {};
io.sockets.on('connection', newConnection);
function newConnection(socket) {
socket.on('add-user', function(user) {
connections[user.id] = {
"socket": socket.id
};
});
socket.on('chat-message', function(message) {
console.log(message);
if (connections[message.receiver]) {
console.log("Send to: " + connections[message.receiver].socket);
// Here are some varients of the emit command. Seems like they all do the same
//io.sockets.connected[connections[message.receiver].socket].emit("chat-message", message);
//io.to(connections[message.receiver].socket).emit("chat-message", message);
socket.broadcast.to(connections[message.receiver].socket).emit("chat-message", message);
} else {
console.log("Send push notification")
}
});
//Removing the socket on disconnect
socket.on('disconnect', function() {
console.log("The client disconnected");
for (var id in connections) {
if (connections[id].socket === socket.id) {
delete connections[id];
}
}
})
}
“ console.log(message);”在消息处理程序中仅被调用一次。这对我来说是令人困惑的部分。如果处理程序被调用两次,为什么只打印一次?尽管如此,在我的快速代码中的处理程序上,用于接收消息的处理程序被多次调用。