2013-12-21 202 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