WebSocket 处理错误 |
您所在的位置:网站首页 › 网络可用性只有我是怎么回事 › WebSocket 处理错误 |
WebSocket 处理错误,当在客户端和服务器之间建立了连接,就会从Web Socket实例触发 open 事件。在通信期间发生的错误会生成错误。它是在 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."); } } } 接收错误消息的示例以下程序说明如何使用WebSocket显示错误消息 – WebSocket Test 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('ERROR: ' + 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); WebSocket Test在浏览器中打开上面代码文件,得到以下结果: |
今日新闻 |
点击排行 |
|
推荐新闻 |
图片新闻 |
|
专题文章 |
CopyRight 2018-2019 实验室设备网 版权所有 win10的实时保护怎么永久关闭 |