我有简单的 web 套接字 html5,当服务器启动时一切正常 问题是当我关闭服务器时(用于测试) 我得到:
WebSocket connection to 'ws://127.0.0.1:7777/api' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
如果发生此错误,我无法捕捉到它永远不会跳转到 onerror 或 onclose
init: function () {
this.m_wsiSendBinary = new WebSocket("ws://127.0.0.1:7681/wsapi");
this.m_wsiSendBinary.onopen = function(evt) {
cc.log("Send Binary WS was opened.");
};
this.m_wsiSendBinary.onmessage = (function(evt) {
this.handleServerResponse(yStr);
this.m_wsiSendBinary.onerror = function(evt) {
};
this.m_wsiSendBinary.onclose = function(evt) {
cc.log("m_wsiSendBinary websocket instance closed.");
self.m_wsiSendBinary = null;
};
}).bind(this);
最佳答案
我没有完整的答案,但是我处理过类似的问题并且有一个部分的而不是那么优雅的解决方案(但可能会帮助某人)。不幸的是没有消除错误信息。
两个业务需求:
- BR1 - 在服务器不可用时处理初始化状态。
- BR2 - 服务器停止时处理状态。
BR1 的解决方案
var global_connection_openned=null;//Here you have the result
init: function () {
global_connection_openned=false;
this.m_wsiSendBinary = new WebSocket("ws://127.0.0.1:7681/wsapi");
this.m_wsiSendBinary.onopen = function(evt)
{
global_connection_openned=true;
};
BR2 的解决方案(假设是 BR1)
//somewhere in your project called by setInterval(..) which will detect the connection is lost (and tries to reestablish/reopen the connetion.
{
if (this.m_wsiSendBinary==null || this.m_wsiSendBinary.readyState==3)
this.init();
if (!global_connection_openned)
this.m_wsiSendBinary=null;
}
无论如何,我真的很好奇这个用例是否有可靠和适当的解决方案。
关于html - ws 如何捕获:WebSocket 连接到 'ws://failed:连接建立时出错:net::ERR_CONNECTION_REFUSED,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38670023/