【发布时间】:2021-07-26 05:12:57
【问题描述】:
身份验证失败后,在断开连接之前,我想向客户端发出一个事件,通知请求提供的令牌无效。在我的 WebSocketGateway 这是我的代码:
handleConnection(client: Socket, ...args: any[]) {
try {
this.socketAuthService.authenticate(client);
this.logger.log(`Client connected: ${client.id}`);
} catch (e) {
this.logger.error(`Client ${client.id} tried to connect with invalid token`);
client.emit('unauthorized', 'Invalid Token');
client.disconnect();
this.logger.log(`Client disconnected due to invalid token: ${client.id}`);
}
}
我的客户:
this.socket.on('unauthorized', (msg) => {
console.log(msg);
});
未发送/接收事件。有什么想法吗?
干杯
【问题讨论】:
-
socketAuthService.authenticate同步吗? -
是的,它是同步的
-
你使用了保护。或者控制台所有
Client disconnected due to invalid token:可能是你的客户端在函数handleConnection运行之前断开了 -
不,它已连接,直到我断开客户端。该事件根本没有发出。我使用allowFunction() 对问题进行了排序。我更喜欢这个想法,因为它甚至不让套接字连接,我不喜欢的是它不允许我抛出 401,而是发送一个 CORS 错误
标签: socket.io nestjs nestjs-gateways