🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
~~~ <!DOCTYPE HTML> <html > <head > <meta charset="utf-8" > <script src="http://libs.baidu.com/jquery/2.1.4/jquery.min.js" ></script > </head > <body > <form > <div id="div1" ></div > <hr > <textarea style="width: 300px;height: 100px;" id="content" ></textarea > <input type="button" value="发送" onclick="Send()" > </form > </body > <script > var ws; var wsUrl = "ws://www.51websocket.cn/message?groupid=22&userid=111&name=李四"; var wsReconnect = false; //避免重复链接 var time1 = 10 * 60 * 1000; //心跳检测 var time2 = 10 * 1000; //断线重连 var tt; createWebSocket(wsUrl); function createWebSocket() { try { ws = new WebSocket(wsUrl); init(); } catch (e) { console.log('catch'); reconnect(wsUrl); } } function init() { //连接关闭时触发 ws.onclose = function () { console.log('Close'); reconnect(wsUrl); }; //通信发生错误时触发 ws.onerror = function () { console.log('Error'); reconnect(wsUrl); }; //连接建立时触发 ws.onopen = function () { //心跳检测重置 console.log('Connect'); heartCheck.start(); }; //客户端接收服务端数据时触发 ws.onmessage = function (event) { $("#div1").prepend("<h3>" + event.data + "</h3>"); } } //心跳检测 var heartCheck = { timeout: time1, timeoutObj: null, serverTimeoutObj: null, start: function () { var self = this; this.timeoutObj && clearTimeout(this.timeoutObj); this.serverTimeoutObj && clearTimeout(this.serverTimeoutObj); this.timeoutObj = setTimeout(function () { console.log("heartCheck"); ws.send("ping www.51websocket.cn"); self.serverTimeoutObj = setTimeout(function () { ws.close(); // createWebSocket(); }, self.timeout); }, this.timeout) } }; //断线重连 function reconnect(url) { if (wsReconnect) { return; } wsReconnect = true; console.log("ReConnect"); //没连接上会一直重连,设置延迟避免请求过多 tt && clearTimeout(tt); tt = setTimeout(function () { createWebSocket(url); wsReconnect = false; }, time2); } function Send() { ws.send($("#content").val()); $("#content").val(""); } </script > </html > ~~~