在客户端和服务器之间建立连接后,将从Web Socket实例触发 open 事件.在通信期间发生的错误会生成错误.它是在 onerror 事件的帮助下标记的. Onerror 之后总是会终止连接.
当通信之间发生错误时会触发 onerror 事件.事件 onerror 之后是连接终止,这是关闭事件.
一个好的做法是始终通知用户关于意外错误并尝试重新连接它们.
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("You are Online"); }else { alert("You are Offline"); }
离线模式表示设备未连接或用户已从浏览器工具栏中选择离线模式.
以下是告知用户网络不可用的方法,并在发生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 Sockets : 显示错误消息;
<!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>
输出如下 :