我的网络应用需要定期检查服务器是否已启动。这允许用户以任一顺序启动服务器和客户端。
为此,我只需从 setTimeout
处理程序内部调用 WebSocket
构造函数。
从使用的 Angular 来看,这种策略效果很好,但是对于我这个开发者来说很烦人,因为我在 Chrome 中看到了很多控制台错误:
remote.html:194 WebSocket connection to 'ws://localhost:8082/' failed: Connection closed before receiving a handshake response
remote.html:194 WebSocket connection to 'ws://localhost:8082/' failed: Connection closed before receiving a handshake response
remote.html:194 WebSocket connection to 'ws://localhost:8082/' failed: Connection closed before receiving a handshake response
这些并不是真正的错误,因为我的 Web 应用程序在服务器不可用的情况下完全正常。它重复调用 WebSocket
构造函数(MDN)只是为了检查服务器是否已经启动。
有没有更好的方法来做到这一点?就上下文而言,我的 Web 应用程序是在设备上运行的原生 C++ 应用程序的“远程控制”。
最佳答案
使用 SharedWorker
时会抑制错误!请尝试以下操作:
main.html
<!doctype html>
<html>
<head>
<title>WS Test</title>
<script type="text/javascript"> (async () => {
await new Promise(r => window.addEventListener('load', r));
let worker = new SharedWorker('worker.js');
worker.port.onmessage = evt => console.log('MSG:', evt.data);
})() </script>
</head>
<body></body>
</html>
worker.js
let ports = [];
onconnect = ({ ports: [ port ] }) => ports.push(port);
(async () => {
while (true) {
await new Promise(r => setTimeout(r, 1000));
let ws = new WebSocket('ws://localhost:9999/');
ws.addEventListener('error', evt => ports.forEach(port => port.postMessage('error')));
ws.addEventListener('open', evt => ports.forEach(port => port.postMessage('open')));
}
})();
这让我反馈 WebSocket
遇到 Error
,但不会在日志中产生任何额外的噪音:
(请注意,“一些消息已移至问题面板”是由于仓促的不符合标准的测试 html - 如果您将此解决方案转移到您自己的代码中,它将消失!)
SharedWorker
没有指向任何特定选项卡的必要链接 - 因此,我看不出为什么 SharedWorker
的错误会在选项卡的任何环境中的控制台。
关于javascript - 检查 WebSocket 服务器是否可用且不出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66468843/