2013-12-21 163 views
0

我正在使用Node.js和WebSocket创建基本的一对一聊天。每次客户端连接时,都会发送他们的ID以及salt + id的MD5哈希值。然后,他们需要与另一个客户端配对。当他们配对时,他们会发送salt + partnerid的ID和MD5哈希。每次发送消息时,都会检查哈希。这是为了确保它们不能只改变Javascript ID变量的值并重新路由它们的消息。Pair WebSocket客户端

的一部分[] 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的那些,但我认为跟踪客户端服务器端可能更容易。我应该做哪一个,代码是什么样的?

回答

2

而不是从服务器广播到每个客户端进行活动,为什么不通过检查从聊天中断开的客户端数量并请求合作伙伴来跟踪服务器。使用这些数据,您可以将从队列中取出所需的客户端进行配对。您还可以确保您正在配对仅请求配对的客户。

+0

我做到了你的建议。如果有人看到这个有兴趣看到的代码,它的源代码在https://github.com/OvalBit/Sigma –

+0

伟大的工作伴侣。从来没有与node.js合作从一般意义上回答了这个问题。 – xvidun