【问题标题】:Angular 6 authentificate client after server restart socket.io socketio-jwt服务器重新启动socket.io socketio-jwt后Angular 6验证客户端
【发布时间】: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


    【解决方案1】:

    这是因为每当您的服务器/客户端脱机时,都会创建一个新套接字用于重新连接目的并建立一个新连接,即重新连接,服务器断开与同一客户端的所有先前连接,此过程是异步的,因此开发人员不容易看到。

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

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

    还有一种可能是你的客户端重新连接设置为false,你可以通过如下的consolution来检查你的socket属性:

    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()
    });
    

    【讨论】:

    • 看来你是对的。我这样做了,没关系。public initSocket(): void { this.socket = socketIo(SERVER_URL, { reconnection: true, }); console.log('Socket init at' + SERVER_URL); this.auth(); this.socket.on('reconnect', (error, callback) => { console.log('reconnect succesfully', this); this.socket.io.reconnect(); this.auth(); }); } private auth() { this.socket.emit('authenticate', { token: this.login.token });}
    猜你喜欢
    • 2016-08-16
    • 2013-01-07
    • 1970-01-01
    • 1970-01-01
    • 2018-04-05
    • 2019-12-09
    • 1970-01-01
    • 1970-01-01
    • 2010-11-20
    相关资源
    最近更新 更多