gpt4 book ai didi

javascript - 配对 WebSocket 客户端

转载 作者:行者123 更新时间:2023-12-02 17:59:03 27 4
gpt4 key购买 nike

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

[部分]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)}

我想到寻找合作伙伴的一种方法是向所有客户发送一条消息,询问他们是否有合作伙伴,然后匹配那些回答错误的客户,但我认为这可能更容易跟踪客户端服务器端。我应该做什么,代码会是什么样子?

最佳答案

与其从服务器向每个客户端广播事件,不如通过检查与聊天断开连接的客户端数量并请求合作伙伴来在服务器中进行跟踪。使用此数据,您可以通过从队列中取出所需的客户端来对它们进行配对。您还可以确保与仅请求配对的客户端进行配对。

关于javascript - 配对 WebSocket 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20715638/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com