【问题标题】:ws how to catch : WebSocket connection to 'ws:// failed: Error in connection establishment: net::ERR_CONNECTION_REFUSEDws 如何捕获:到 'ws:// 的 WebSocket 连接失败:连接建立错误:net::ERR_CONNECTION_REFUSED
【发布时间】:2016-07-30 03:14:47
【问题描述】:

我有简单的 web sockets 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);

【问题讨论】:

    标签: html websocket


    【解决方案1】:

    我没有完整的答案,但是我处理了类似的问题并且有一个部分且不那么优雅的解决方案(但可能会帮助某人)。遗憾的是没有消除错误信息。

    两个业务需求:

    • 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;
    }
    

    无论如何,我真的很好奇这个用例是否有可靠且适当的解决方案。

    【讨论】:

    • 为什么需要全局变量?检查 WS 状态还不够?
    猜你喜欢
    • 2016-01-29
    • 1970-01-01
    • 2015-12-17
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    • 2017-11-18
    • 1970-01-01
    相关资源
    最近更新 更多