首页 > 解决方案 > 服务器重新启动socket.io socketio-jwt后Angular 6验证客户端

问题描述

我想在服务器端验证 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.jsangularsocket.iojwt

解决方案


这是因为每当您的服务器/客户端离线时,都会创建一个新的套接字用于重新连接目的并建立一个新的连接,即重新连接,服务器断开它与同一个客户端的所有先前连接,这个过程是异步的,因此不可见给开发者很容易。

我还会检查我完成的套接字重新连接是否重新连接到,默认情况下套接字重新连接到您的客户端连接到的端口。

如果是这种情况,那么您需要在 io (套接字管理器)的帮助下重新连接

也有可能您的客户端重新连接设置为 false,您可以通过如下控制台来检查您的套接字属性:

this.socket.on('disconnect', function (error) {
    console.log('disconnected', this)
    //this sets whether the re connection is allowed or not
    this.io._reconnection = true;
});

this.socket.on('reconnect', (error, callback) => {
    console.log('reconnect succesfully', this);
    //connect to the previously connected socket.
    this.io.socket.reconnect()
});

推荐阅读