Javascript 配对WebSocket客户端
我正在使用Node.js和WebSocket创建一个基本的一对一聊天。每次客户端连接时,都会向它们发送ID和salt+ID的MD5哈希。然后,它们需要与另一个客户端配对。当它们配对时,会向它们发送salt+partnerid的ID和MD5哈希。每次发送消息时,都会检查哈希。这是为了确保他们不能仅仅更改Javascript ID变量的值并重新路由消息 [部分]server.jsJavascript 配对WebSocket客户端,javascript,node.js,websocket,Javascript,Node.js,Websocket,我正在使用Node.js和WebSocket创建一个基本的一对一聊天。每次客户端连接时,都会向它们发送ID和salt+ID的MD5哈希。然后,它们需要与另一个客户端配对。当它们配对时,会向它们发送salt+partnerid的ID和MD5哈希。每次发送消息时,都会检查哈希。这是为了确保他们不能仅仅更改Javascript ID变量的值并重新路由消息 [部分]server.js var salt = "kPNtvp2UoBQRBcJ"; var count = 0; var clients = {
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
的客户,但我认为在服务器端跟踪客户可能更容易。我应该做哪一个,代码是什么样子的?与其从服务器向每个客户端广播活动,不如通过检查与聊天中断开的客户端数量并请求合作伙伴来跟踪服务器。使用这些数据,您可以通过从队列中取出所需的客户端来配对它们。您还可以确保您正在配对仅请求配对的客户端 我是按照你的建议做的。如果有人想看这段代码,源代码将在Great work mate上发布。从未使用过node.js从一般角度回答了这一问题。