我正在使用Node.js和WebSocket创建一个基本的一对一聊天。每次客户端连接时,都会向他们发送他们的ID,以及salt + id的MD5哈希值。然后,他们需要与另一个客户配对。当它们配对时,会向它们发送salt + partnerid的ID和MD5哈希值。每次发送消息时,都会检查散列。这是为了确保他们不仅可以更改Javascript ID变量的值并重新路由他们的消息。
[strong> server.js
的一部分var salt = "kPNtvp2UoBQRBcJ";
var count = 0;
var clients = {};
wsServer.on('request', function(r){
var connection = r.accept('echo-protocol', r.origin);
var id = count++;
clients[id] = connection;
console.log((new Date()) + ' Connection accepted [' + id + ']');
clients[id].sendUTF(JSON.stringify({"type": "id", "id": id, "hash": md5(salt+id)}));
connection.on('message', function(message) {
var data = JSON.parse(message.utf8Data);
console.log((new Date()) + ' New ' + data.type + ' sent from ' + data.from.id + ' to ' + data.to.id + ': ' + data.message);
if(checkHash(data.from.id, data.from.hash) && checkHash(data.to.id, data.to.hash)){
clients[data.to.id].sendUTF(message.utf8Data);
clients[data.from.id].sendUTF(message.utf8Data);
}else{
console.log((new Date()) + ' Client hashes invalid, alerting sender and intended recipient.');
clients[data.from.id].sendUTF(JSON.stringify({"type": "message", "message": "Our system has detected that you attempted to reroute your message by modifying the Javascript variables. This is not allowed, and subsequent attempts may result in a ban. The user you attempted to contact has also been notified.", "from": {"id": "system", "hash": ""}, "to": {"id": data.to.id, "hash": ""}}));
clients[data.to.id].sendUTF(JSON.stringify({"type": "message", "message": "Someone you are not chatting with just attempted to send you a message by exploiting our system, however we detected it and blocked the message. If you recieve any subsequent messages that seem unusual, please be sure to report them.", "from": {"id": "system", "hash": ""}, "to": {"id": data.to.id, "hash": ""}}));
}
});
connection.on('close', function(reasonCode, description) {
delete clients[id];
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
});
});
现在一切正常,但我的问题是将客户配对。为了配对它们,必须向两个客户端发送一条消息,如下所示:
{"type": "partner", "id": PARTNERID, "hash": md5(sald+id)}
我想找到合作伙伴的一种方法是向所有客户发送消息,询问他们是否有合作伙伴,然后匹配回复false
的客户,但我认为可能更容易跟踪客户服务器端。我应该做哪一个,代码是什么样的?
答案 0 :(得分:2)
不是从服务器向每个客户端广播活动,为什么不通过检查与聊天断开连接的客户端数量并请求合作伙伴来跟踪服务器。使用此数据,您可以将从队列中获取所需的客户端配对。您还可以确保配对仅请求配对的客户端。