2014-04-14 5 views
23

내 페이지가로드되면 서버에 연결을 시도하라는 메시지가 표시되지만 작동하지 않습니다. 이 스크립트 블록 내 파일의 상단에 있습니다 :잡히지 않은 InvalidStateError : 'WebSocket'에서 'send'를 실행하지 못했습니다. 여전히 연결 상태입니다.

var connection = new WrapperWS(); 
connection.ident(); 
// var autoIdent = window.addEventListener('load', connection.ident(), false); 

대부분의 시간, 나는 제목에 오류 참조 : 그래서 catch 예외로 시도

Uncaught InvalidStateError: Failed to execute 'send' on 'WebSocket': Still in CONNECTING state

가 같은 당신이 볼 수 있습니다 아래에 있지만 지금은 InvalidStateError이 정의되어 있지 않으며 그 값은 ReferenceError입니다.

// Define WrapperWS 

function WrapperWS() { 
    if ("WebSocket" in window) { 
     var ws = new WebSocket("ws://server:8000/"); 
     var self = this; 

     ws.onopen = function() { 
      console.log("Opening a connection..."); 
      window.identified = false; 
     }; 
     ws.onclose = function (evt) { 
      console.log("I'm sorry. Bye!"); 
     }; 
     ws.onmessage = function (evt) { 
      // handle messages here 
     }; 
     ws.onerror = function (evt) { 
      console.log("ERR: " + evt.data); 
     }; 

     this.write = function() { 
      if (!window.identified) { 
       connection.ident(); 
       console.debug("Wasn't identified earlier. It is now."); 
      } 
      ws.send(theText.value); 
     }; 

     this.ident = function() { 
      var session = "Test"; 
      try { 
       ws.send(session); 
      } catch (error) { 
       if (error instanceof InvalidStateError) { 
        // possibly still 'CONNECTING' 
        if (ws.readyState !== 1) { 
         var waitSend = setInterval(ws.send(session), 1000); 
        } 
       } 
      } 
     window.identified = true; 
      theText.value = "Hello!"; 
      say.click(); 
      theText.disabled = false; 
     }; 

    }; 

} 

내가 우분투에 크롬을 사용하여 테스트입니다 :

여기 내 웹 소켓 연결을위한 랩퍼 오브젝트입니다.

답변

20

readyState가 그런 다음 ws.send 대신에 this.send를 사용 1.

this.send = function (message, callback) { 
    this.waitForConnection(function() { 
     ws.send(message); 
     if (typeof callback !== 'undefined') { 
      callback(); 
     } 
    }, 1000); 
}; 

this.waitForConnection = function (callback, interval) { 
    if (ws.readyState === 1) { 
     callback(); 
    } else { 
     var that = this; 
     // optional: implement backoff for interval here 
     setTimeout(function() { 
      that.waitForConnection(callback, interval); 
     }, interval); 
    } 
}; 

을, 그리고 콜백에서 이후에 실행되어야하는 코드를 넣어 당신은 대기 프록시 기능을 통해 메시지를 보낼 수 :

this.ident = function() { 
    var session = "Test"; 
    this.send(session, function() { 
     window.identified = true; 
     theText.value = "Hello!"; 
     say.click(); 
     theText.disabled = false; 
    }); 
}; 

더욱 간소화 된 사항은 promises입니다.

+3

'setTimeout'에서 호출 할 때'that.waitForConnection (callback, interval)'에'interval' 매개 변수를 넣는 것을 잊었을 것입니다. –

관련 문제