一旦在客户端和服务器之间建立了连接,就会从Web Socket实例中触发一个打开事件。在通信过程中会因错误而产生错误。它标记为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连接。
想象一下,您的用户正在使用您的Web应用程序,而当网络连接突然在执行任务时变得无响应时。在现代的本机桌面和移动应用程序中,检查网络可用性是一项常见任务。
最常见的方法是简单地向应该正常运行的网站(例如http://www.google.com)发出HTTP请求。如果请求成功,则台式机或移动设备将知道存在活动连接。类似地,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套接字显示错误消息-
<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>
输出如下-
Made with ❤️ in Chengdu. Copyright reserved 2019-2022.
蜀ICP备20006366号-1