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
的那些,但我認爲跟蹤客戶端服務器端可能更容易。我應該做哪一個,代碼是什麼樣的?
我做到了你的建議。如果有人看到這個有興趣看到的代碼,它的源代碼在https://github.com/OvalBit/Sigma –
偉大的工作伴侶。從來沒有與node.js合作從一般意義上回答了這個問題。 – xvidun