【发布时间】:2019-04-06 12:59:19
【问题描述】:
我想在服务器端验证 eacht socket.io 事件。
当我首先打开角度页面时,调用方法initSocket(login: Login),没关系。
验证成功,我可以向服务器发送消息。
但是,如果我重新启动服务器,则通过 Http 重新连接到服务器,但无法通过 socketio 发送消息。
在我的服务器中,日志中没有消息。
似乎 socketio-jwt 阻止了客户端消息。
如果我在客户端按 F5,它仍然可以。
如何在不刷新页面的情况下解决它?
在建立连接后,我似乎必须将令牌传递给客户端的每个事件,但我不知道该怎么做。
角度 6:
public initSocket(login: Login): void {
this.socket = socketIo(SERVER_URL);
console.log('Socket init at' + SERVER_URL);
this.socket.emit('authenticate', { token: this.login.token });
this.socket.on('authenticated', function () {
console.log('socket is jwt authenticated');
});
this.socket.on('unauthorized', function (error, callback) {
if (error.data.type === 'UnauthorizedError' || error.data.code === 'invalid_token') {
// redirect user to login page perhaps or execute callback:
callback();
console.error('Users token has expired');
}
});
this.socket.on('disconnect', function (error) {
console.error('socket disconnect', error);
});
this.socket.on('connect_failed', function (error) {
console.error('socket connect_failed');
});
}
服务器端:
io.sockets
.on('connection', socketioJwt.authorize({
secret: environment.secret,
timeout: 15000,
callback: false
})).on('authenticated', function (socket) {
clients[socket.decoded_token.id] = socket.decoded_token.login;
console.error('Connected: ', socket.decoded_token.login);
socket.on('message', async function (data) {
try {
// Проверка что пользователь пишите от себя
if (data.from === socket.decoded_token.id) {
data.totalCount = await db_helper.saveMessage(data);
if (clients[data.from] && clients[data.to]) {
io.sockets.connected[clients[data.to].socket].emit("message", data);
console.log("Sending from: " + clients[data.from].name + " to: " + clients[data.from].name + " '" + data.text + "'");
} else {
console.log('User does not exist: from=>', data.from, ':', clients[data.from], 'to=>', data.to, ':', clients[data.to]);
}
}
}
catch (error) {
console.error(error.message);
}
});
//Removing the socket on disconnect
socket.on('disconnect', function () {
});
});
【问题讨论】:
标签: node.js angular socket.io jwt