ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
~~~ <!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 wsCopy; var wsUrl = "ws://127.0.0.1:8095/message?groupid=22&userid=111&name=李四"; //连接状态 var wsConnStatus = false; //心跳检测 var heartTimeOut = 10 * 1000; //10s (1000 毫秒= 1 秒) - 设置时间比nginx超时时间短) //断线重连 var reConnTimeOut = 2 * 1000; //心跳检测 var heartCheck = { timer: null, timeout: heartTimeOut, start: function (ws) { this.timer = setInterval(function () { console.log("heartCheck"); ws.send("ping www.51websocket.cn"); }, this.timeout); } }; //断线重连 var reConnection = { tag: false, timer: null, timeout: reConnTimeOut, url: wsUrl, start: function (ws) { if (!ws.wsConnStatus) { this.timer = setTimeout(function () { console.log("ReConnect"); createWebSocket(this.url); }, this.timeout); return; } return; } }; createWebSocket(wsUrl); function createWebSocket() { try { var ws = new WebSocket(wsUrl); init(ws); } catch (e) { console.log('catch'); reConnection.start(); } } function init(ws) { //连接关闭时触发 ws.onclose = function () { //关闭心跳检测 clearInterval(heartCheck.timer); if (this.wsConnStatus == undefined) { this.wsConnStatus = false; } else if (this.wsConnStatus == false) { this.wsConnStatus = true; } reConnection.tag = true; console.log('Close'); reConnection.start(this); }; //通信发生错误时触发 ws.onerror = function () { if (this.wsConnStatus == undefined) { this.wsConnStatus = false; } else if (this.wsConnStatus == false) { this.wsConnStatus = true; } console.log('Error'); reConnection.start(this); }; //连接建立时触发 ws.onopen = function () { clearTimeout(reConnection.timer); wsConnStatus = true; console.log('Connect'); reConnection.tag = false; //心跳检测重置 heartCheck.start(this); ws2 = ws; }; //客户端接收服务端数据时触发 ws.onmessage = function (event) { $("#div1").append("<h3>" + event.data + "</h3>"); } } function Send() { ws2.send($("#content").val()); $("#content").val(""); } </script > </html > ~~~