在浏览器中同步关闭websocket

罗宾·休伊

我有一个WebSocket用于连接服务器并执行操作的Web应用程序操作完成后,连接将自动关闭。但是用户可以通过按下按钮来重新启动操作,该按钮将关闭连接,然后创建一个新连接。

用户重新启动操作时的示例代码:

if (this.connection) {
    this.connection.close()
    // this.connection = null
}

if (!this.connection) {
    this.connection = new WebSocket(serverSocketURL)

    // Other logic codes here

    this.connection.onclose = () => {
        this.connection = null
    }
}

问题在于close()方法是异步的,因此第二个块代码在关闭连接之前运行。如何同步关闭WebSocket连接?我应该setTimeout在调用close()方法后等待一小段时间吗?

Jaromanda X

也许这会做你想要的

当用户“重新连接”连接时,将close添加第二个侦听器以建立新的连接-由于此侦听器是在set侦听器之后添加的this.connection = null,因此它将在运行后被调用,因此没有机会比赛条件

const makeConnection = () => {
    this.connection = new WebSocket(serverSocketURL);
    // Other logic codes here
    this.connection.addEventListener('close', () => {
        this.connection = null
    });
};
if (this.connection) {
    this.connection.addEventListener('close', makeConnection);
    this.connection.close();
} else {
    makeConnection();
}

或-使用onclose代替addEventListener('close',

const makeConnection = () => {
    this.connection = new WebSocket(serverSocketURL);
    // Other logic codes here
    this.connection.onclose = () => {
        this.connection = null
    };
};
if (this.connection) {
    this.connection.onclose = makeConnection;
    this.connection.close();
} else {
    makeConnection();
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章