當在客戶端和服務器之間建立了連接,就會從Web Socket實例觸發open
事件。在通信期間發生的錯誤會生成錯誤。它是在onerror
事件的幫助下標記和處理的。在發生錯誤之後總是會終止連接。
當通信之間發生錯誤時會觸發onerror
事件。事件onerror
之後是連接終止,這是一個關閉事件。
一個好的做法是始終告知用戶意外錯誤並嘗試重新連接它們。
var wsUri = "wss://echo.websocket.org/";
var socket = new WebSocket(wsUri);
socket.onclose = function(event) {
console.log("Error occurred.");
// Inform the user about the error.
var label = document.getElementById("status-label");
label.innerHTML = "Error: " + event;
}
在處理錯誤時,必須考慮內部和外部參數。
- 內部參數包括由於代碼中的錯誤或意外的用戶行為而可能生成的錯誤。
- 外部錯誤與應用程式無關; 它們與參數無關,而這些參數無法控制。最重要的是網路連接。
- 任何互動式雙向Web應用程式都需要有效的Internet連接。
檢查網路可用性
想像一下,當用戶正在使用網路應用時,突然網路連接在任務中間變得無法回應。在現代本機桌面和移動應用程式中,檢查網路可用性是一項常見任務。
最常見的方法是向一個應該啟動的網站發出HTTP請求(例如,http://www.google.com)。 如果請求成功,則桌面或移動設備知道存在活動連接。類似地,HTML可使用XMLHttpRequest
來確定網路可用性。
但是,HTML5使它變得更加容易,並引入了一種檢查流覽器是否可以接受Web回應的方法。這是通過導航器對象實現的 -
if (navigator.onLine) {
alert("網路連接正常");
}else {
alert("網路連接好像出現問題");
}
離線模式表示設備未連接或用戶已從流覽器工具欄中選擇離線模式。以下是如何通知用戶網路不可用並嘗試在發生WebSocket關閉事件時重新連接 -
socket.onclose = function (event) {
// Connection closed.
// Firstly, check the reason.
if (event.code != 1000) {
// Error code 1000 means that the connection was closed normally.
// Try to reconnect.
if (!navigator.onLine) {
alert("You are offline. Please connect to the Internet and try again.");
}
}
}
接收錯誤消息的示例
以下程式說明如何使用Web套接字顯示錯誤消息 -
<!DOCTYPE html>
<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.onerror = function(evt) {
onError(evt)
};
}
function onOpen(evt) {
writeToScreen("CONNECTED");
doSend("WebSocket rocks");
}
function onClose(evt) {
writeToScreen("DISCONNECTED");
}
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>
在流覽器中打開上面代碼檔,得到以下結果:
上一篇:
WebSocket打開連接
下一篇:
Websocket接收和發送消息