在浏览器中同步关闭websocket

时间:2018-08-27 09:26:53

标签: javascript websocket

我有一个使用import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; import { AppComponent } from './app.component'; import { HelloComponent } from './hello.component'; @NgModule({ imports: [ BrowserModule, FormsModule, HttpClientModule ], declarations: [ /*Your Components Here*/ ], bootstrap: [ AppComponent ] }) export class AppModule { } 连接服务器并执行操作的Web应用程序。操作完成后,连接将自动关闭。 但是用户可以通过按一个按钮来重启操作,该按钮会关闭连接,然后创建一个新的连接。

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

WebSocket

问题是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等待一会儿吗?

1 个答案:

答案 0 :(得分:1)

也许这会做您想要的

当用户“重新连接”连接时,将添加第二个close侦听器以建立新的连接-由于此侦听器是在设置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();
}