2013-05-18 52 views
3

我有這個簡單的WebSocket問題如何在Javascript中使用close函數訪問onclose事件代碼?

<!DOCTYPE html> 
<meta charset="utf-8" /> 
<title>WebSocket Test</title> 
<script language="javascript" type="text/javascript"> 
    var wsUri = "ws://echo.websocket.org/"; 
    var output; 

    function init() { 
     output = document.getElementById("output"); 
     testWebSocket(); 
    } 
    function testWebSocket() { 
     websocket = new WebSocket(wsUri); 
     websocket.onopen = function (evt) { 
      onOpen(evt) 
     }; 
     websocket.onclose = function (evt) { 
      onClose(evt) 
     }; 
     websocket.onmessage = function (evt) { 
      onMessage(evt) 
     }; 
     websocket.onerror = function (evt) { 
      onError(evt) 
     }; 
    } 
    function onOpen(evt) { 
     writeToScreen("CONNECTED"); 
     doSend("WebSocket rocks"); 
    } 
    function onClose(evt) { 
     writeToScreen("DISCONNECTED"); 
    } 
    function onMessage(evt) { 
     writeToScreen('<span style="color: blue;">RESPONSE: ' + evt.data + '</span>'); 
     websocket.close(); 
    } 
    function onError(evt) { 
     writeToScreen('<span style="color: red;">ERROR:</span> ' + evt.data); 
    } 
    function doSend(message) { 
     writeToScreen("SENT: " + message); 
     websocket.send(message); 
    } 
    function writeToScreen(message) { 
     var pre = document.createElement("p"); 
     pre.style.wordWrap = "break-word"; 
     pre.innerHTML = message; 
     output.appendChild(pre); 
    } 
    window.addEventListener("load", init, false); 
</script> 
<h2>WebSocket Test</h2> 
<div id="output"></div> 

</html> 

我的問題是,我怎麼能訪問網絡套接字關閉代碼? 在本網站上所提到

https://developer.mozilla.org/en-US/docs/WebSockets/WebSockets_reference/CloseEvent

1001 CLOSE_GOING_AWAY 
1000 CLOSE_NORMAL 
1005 CLOSE_NO_STATUS 
1006 CLOSE_ABNORMAL 

現在這是我的OnClose功能

function onClose(evt) { writeToScreen("DISCONNECTED"); } 

我都忍了警報爲警報(EVT),但我沒有得到任何關閉代碼。

有誰請幫助

回答

10

試試這個:

function onClose(event) 
{ 
    alert('Onclose called' + event); 
    alert('code is' + event.code); 
    alert('reason is ' + event.reason); 
    alert('wasClean is' + event.wasClean); 
} 
+3

第一個警報將只產生一個沒用'[對象的對象]' –

+1

應該是'警報( '的OnClose稱爲' + JSON.stringify(事件));' –

+0

不,這應該是'JSON.stringify(event,Object.getOwnPropertyNames(event))'因爲[否則很多屬性將不會顯示](https://stackoverflow.com/questions/44815172/log - 顯示錯誤-對象istrustedtrue-代替-的-實際誤差數據)。 –