方式1、使用第三方庫實現html
好比:reconnecting-websocket.js
ReconnectingWebSocket,代碼:https://github.com/joewalnes/reconnecting-websocketjava
var ws = new WebSocket('ws://....');
替換成下面的
var ws = new ReconnectingWebSocket('ws://....');
方式2、本身用setTimeout實現git
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>socketjs</title> </head> <body> 發送者:<input id="fromUserId" value="2"> 接收者:<input id="toUserId" value="3"> <button type="button" onclick="openClick();">打開</button> <button type="button" onclick="closeClick();">關閉</button><br/> <input id="message" value="---"/> <button type="button" onclick="sendClick();">發送</button> <div id="content"></div> <script> var socket; var t; var MAX = 1000; var count = 0; function openClick() { connection(); } function closeClick() { socket.close(); } function sendClick() { var fromUserId = document.getElementById("fromUserId").value; var toUserId = document.getElementById("toUserId").value; var content = document.getElementById("message").value; var obj = { "fromUserId":fromUserId, "toUserId":toUserId, "content":content }; document.getElementById("content").innerHTML = document.getElementById("content").innerHTML + '<br/>' + fromUserId + "說:" + content; socket.send(JSON.stringify(obj)); console.log(fromUserId + "說:" + JSON.stringify(content)); } var connection = function() { var fromUserId = document.getElementById("fromUserId"); var url = 'ws://' + window.location.host + '/ycxcode/websocket/commodity/{' + fromUserId.value + '}'; socket = new WebSocket(url); socket.onopen = onopen; socket.onmessage = onmessage; socket.onclose = onclose; socket.onerror = onerror; } var reconnection = function() { count = count + 1; console.log("reconnection...【" + count + "】"); //1與服務器已經創建鏈接 if (count >= MAX || socket.readyState == 1) { clearTimeout(t); } else { //2已經關閉了與服務器的鏈接 if (socket.readyState == 3) { connection(); } //0正嘗試與服務器創建鏈接,2正在關閉與服務器的鏈接 t = setTimeout(function() {reconnection();}, 100); } } var onopen = function() { console.log("open..."); } var onclose = function() { console.log("close..."); reconnection(); } var onmessage = function(e) { console.log("message..."); if (e.data === "") return; var toUserId = document.getElementById("toUserId").value; document.getElementById("content").innerHTML = document.getElementById("content").innerHTML + '<br/>' + toUserId + "說:" + e.data; console.log(toUserId + "說:" + e.data); } var onerror = function() { console.log("error..."); reconnection(); } </script> </body> </html>
核心代碼就是在onclose事件發生時調用reconnection()方法,可是要特別注意重試次數和狀態控制。
在socket.readyState == 3(已經關閉了與服務器的鏈接)才真正的發起鏈接,
在socket.readyState == 1(與服務器已經創建鏈接)或重試次數超了設定值就終止重試,但要注意在終止瀏覽器頁面及網絡恢復時重刷頁面
在socket.readyState == 0(正嘗試與服務器創建鏈接)或socket.readyState == 2(正在關閉與服務器的鏈接)時僅僅重試,而不發起鏈接github