我有一个使用 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()
方法是异步的,因此第二个 block 代码在连接关闭之前运行。
如何同步关闭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();
}
关于javascript - 浏览器同步关闭websocket,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52036280/