onerror 回调不会立即调用onclose 是否可以调用?换句话说,是否有可能得到一个 WebSocket
错误,该错误与当时正在关闭的连接不一致?
如果可能的话,我想测试一下这个案例。我有一个使用 node.js 和 express-ws 的模拟后端。后台怎么触发前端的onerror事件回调。
最佳答案
error
事件只会在触发 close
事件之前被触发,至少通过正确实现规范的实现,即你会得到 error
和 close
作为一对,或者只是 close
本身。
process for closing a websocket consists of 3 steps ,如果需要,第二个可以选择性地触发 error
事件:
- If the user agent was required to fail the WebSocket connection, or if the the WebSocket connection was closed after being flagged as full, fire a simple event named
error
at the WebSocket object. [WSP]
在第三步then调用close之前:
- Fire an event named
close
at the WebSocket object, usingCloseEvent
,...
并且因为这两个步骤在同一个排队任务中一个接一个地执行,所以您的事件处理程序应该一个接一个地调用,它们之间没有其他事件或任务发生。
关于javascript - 对于 WebSocket,onclose 总是在 onerror 之后调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40084398/