Twilio Sync:连接被服务器关闭,原因是 TOKEN_EXPIRED

Twilio Sync: connection closed by server, reason is TOKEN_EXPIRED

Twilio 同步超时为 172800

$.getJSON("/dashboard/token", function (response) {
    console.log(`Token Generated at ${new Date()}`);
    localStorage.setItem('syncToken', response.token);
    
    syncClient = new Twilio.Sync.Client(response.token, { logLevel: "info" });

    syncClient.on('tokenAboutToExpire', function () {
        console.log(`tokenAboutToExpire at: ${new Date()}`);
        var token = localStorage.getItem('syncToken');
        syncClient.updateToken(token);
    });
});

这里是 Twilio Sync 浏览器控制台显示:

Twilsock I: socket opened
twilio-sync.js:25304 Twilsock I: refreshing all registrations
twilio-sync.js:25304 Twilsock I: update registration for context 8c430fb3-4353-4b06-9cfd-6bebc78582b0

但一段时间后浏览器中会出现此消息:

Twilsock I: connection has expired
Notify I: Transport ready false 
Twilsock I: connection closed by server, reason is TOKEN_EXPIRED
Twilsock I: socket closed CloseEvent

谁能告诉我如何在 Twilio 同步事件上解决这个问题?

此处为 Twilio 开发人员布道师。

您在那里收到的事件是令牌即将过期,但是您正在用令牌本身替换令牌。相反,您应该从后端请求一个新令牌并使用该新令牌更新客户端。

$.getJSON("/dashboard/token", function (response) {
    console.log(`Token Generated at ${new Date()}`);
    localStorage.setItem('syncToken', response.token);
    
    syncClient = new Twilio.Sync.Client(response.token, { logLevel: "info" });

    syncClient.on('tokenAboutToExpire', function () {
        console.log(`tokenAboutToExpire at: ${new Date()}`);
        $.getJSON("/dashboard/token", function (response) {
            syncClient.updateToken(response.token);
        });
    });
});

谢谢,我尝试了所有事件,所以在这里我明白了...

syncClient.on('connectionStateChanged', (newState) => {
    console.log('Received a new connection state:', newState);
    if (newState === 'disconnecting') {
        $.getJSON("/dashboard/token", function (response) {
            var token = response.token;
            syncClient.updateToken(token);
        });
    }
});