最近在做即时通讯,做了一个web端的js websocket做测试,源代码在这里:
<!DOCTYPE HTML> <html> <head> <title>My WebSocket</title> </head> <body> <input id="text" type="text" /> <button onclick="send()">Send</button> <button onclick="closeWebSocket()">Close</button> <div id="message"></div> </body> <script type="text/javascript" th:inline="javascript"> var websocket = null; var lockReconnect = false; //避免ws重复连接 var listId = [[${listId}]]; //判断当前浏览器是否支持WebSocket, 主要此处要更换为自己的地址 if ('WebSocket' in window) { connectSocket(); } else { alert('Not support websocket') } //连接webSocket function connectSocket(){ try{ websocket = new WebSocket("ws://192.168.0.37:8084/api/rest/ws/chatContent/"+listId); initEvent(); }catch(e){ reconnect(); console.log(e); } } function initEvent(){ //连接发生错误的回调方法 websocket.onerror = function(e) { reconnect(); console.log("llws连接错误!"); setMessageInnerHTML("llws连接关闭!"+new Date().toLocaleString()); }; //连接成功建立的回调方法 websocket.onopen = function(event) { heartCheck.reset().start(); //心跳检测重置 setMessageInnerHTML("llws连接成功!"+new Date().toLocaleString()); } //接收到消息的回调方法 websocket.onmessage = function(event) { heartCheck.reset().start(); console.log("llws收到消息啦:" +event.data); setMessageInnerHTML(event.data); } //连接关闭的回调方法 websocket.onclose = function(e) { reconnect(); console.log("llws连接关闭!"+new Date().toLocaleString()); setMessageInnerHTML("llws连接关闭!"+new Date().toLocaleString()); } } //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。 window.onbeforeunload = function() { websocket.close(); } //将消息显示在网页上 function setMessageInnerHTML(innerHTML) { document.getElementById('message').innerHTML += innerHTML + '<br/>'; } //关闭连接 function closeWebSocket() { websocket.close(); } //发送消息 function send(message) { if(!message){ message = document.getElementById('text').value; } websocket.send(message); } //重连 function reconnect() { if(lockReconnect) return; lockReconnect = true; setTimeout(function () { //没连接上会一直重连,设置延迟避免请求过多 connectSocket(); lockReconnect = false; }, 2000); } //心跳检测 var heartCheck = { timeout: 5000, //1分钟发一次心跳 timeoutObj: null, serverTimeoutObj: null, reset: function(){ clearTimeout(this.timeoutObj); clearTimeout(this.serverTimeoutObj); return this; }, start: function(){ var self = this; this.timeoutObj = setTimeout(function(){ //这里发送一个心跳,后端收到后,返回一个心跳消息, //onmessage拿到返回的心跳就说明连接正常 send("ping"); self.serverTimeoutObj = setTimeout(function(){//如果超过一定时间还没重置,说明后端主动断开了 websocket.close(); //如果onclose会执行reconnect,我们执行ws.close()就行了.如果直接执行reconnect 会触发onclose导致重连两次 }, self.timeout) }, this.timeout) } } </script> </html>