Node.js 如何在连接到节点上的websocket服务器时传递消息
我这里有这个密码-Node.js 如何在连接到节点上的websocket服务器时传递消息,node.js,websocket,Node.js,Websocket,我这里有这个密码- const wss = new SocketServer({ express() }); wss.on('connection', ws => { console.log('Client connected'); ws.on('message', msg => { console.log('received: %s', msg); }); ws.on('close', () => console.log('C
const wss = new SocketServer({ express() });
wss.on('connection', ws => {
console.log('Client connected');
ws.on('message', msg => {
console.log('received: %s', msg);
});
ws.on('close', () => console.log('Client disconnected'));
});
现在出现了一些问题,D-Dos攻击可能会使我的服务器崩溃
在允许陌生人连接到websocket之前,有没有办法检查令牌或其他东西?此外,套接字将位于另一个域上,因此Cookie将无法工作
或者,如果用户在连接后未发送身份验证令牌,是否有方法断开用户的连接
如果它正在运行并且允许每个人无限期地连接,那么这就是一个安全风险。服务器可以很容易地关闭。使用Socket.io可能需要像您一样的设置,请参阅 否则,您必须自己实现它,但您应该遵循一些标准。我能想到的第一个丑陋的手工解决方案是:
wss.on('connection', ws => {
console.log('Client connected');
isAuthenticated = false
ws.on('message', msg => {
if (!isAuthenticated ) {
// check if message is a token
// else comunicates back the error
}
console.log('received: %s', msg);
});
ws.on('close', () => console.log('Client disconnected'));
});
对于DDos攻击,如果他们有一个令牌,他们可以发送无限的请求:同样,你应该自己计算传入的消息速率,并实施类似于节流策略的措施。有没有一种方法可以有效地断开连接x秒后未发送消息的客户端的连接
console.log('client connected'));
您可以放置设置超时(()=>ws.close(),5000)
,并在收到消息时清除该超时。我是否以某种方式帮助过您?是的,特别是这个链接帮助过您-