我有一个使用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
连接? 我是否应该在调用close()
方法后使用setTimeout
等待一小段时间?
也许这会做你想要的
当用户"重新连接"连接时,将添加第二个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();
}