【发布时间】:2022-04-25 23:14:07
【问题描述】:
我正在使用 Socket.io 创建一个 Electron 应用程序。当用户的计算机进入睡眠模式时,服务器会断开与客户端的连接并抛出错误“传输关闭”。当用户尝试重新连接时,我检查令牌是否仍然有效,如果不是,我刷新它们并尝试将它们发送到 socketIo 服务器。
我遇到的问题是,在“reconnect_attempt”上,socket.io 不会等到我刷新令牌以尝试重新连接,它会立即尝试使用旧令牌重新连接,这些令牌被服务器拒绝,这似乎也终止与阻止未来重新连接尝试的用户的连接。
这是我连接到服务器的代码的一部分
module.exports.connect = async (JWT) => {
return new Promise( async resolve => {
console.log("connecting to the server")
const connectionOptions = {
secure: true,
query: {token: JWT},
reconnectionDelay: 4000
}
let socket = await socketIo.connect(`${process.env.SERVER_URL}:${process.env.SERVER_PORT}`, connectionOptions);
resolve(socket)
})
}
这是我的 reconnect_attempt 代码
socket.on('reconnect_attempt', async () => {
const getCurrentJWT = require("../../main").getCurrentJWT;
let JWT = await getCurrentJWT(); //By the time this line returns, socket.io has already tried to reconnect
if(JWT.success) { //if refreshed successfully
console.log("Trying to submit new token......", JWT);
socket.query.token = JWT.JWT;
} else {
console.log("Token not refreshed.")
}
});
这是我在服务器上的一部分
io.use(async (socket, next) => {
let token = socket.handshake.query.token;
//and the instruction from here https://docs.aws.amazon.com/cognito/latest/developerguide/amazon-cognito-user-pools-using-tokens-verifying-a-jwt.html
let tokenIsValid = await checkTokenValidity(token);
if( tokenIsValid ) {
next();
} else {
next(new Error('invalidToken'));
console.log("Not valid token")
}
})
【问题讨论】: