SpringBoot 整合 websocket (五)——前端封装补充

修改构造函数

/**
	 * 构造函数
	 * @param url 路径
	 * @param isAutoConnect 是否自动连接 true/false
	 * @param receiveMsgFun 接收消息后处理函数
	 * @param reconnectTotalNum 重连总的次数,超过了就断开,不填写默认5次
	 * @parma clearConnFun 超过重连次数后触发的函数
	 */
	constructor(url,isAutoConnect,receiveMsgFun,reconnectTotalNum,clearConnFun) {
          
   
		this.reconnectTotalNum = this.isEmpty(reconnectTotalNum) ? 5 : reconnectTotalNum;//重连总次数
		this.clearConnFun=clearConnFun;
		this.reconnectNum= 0; //已重连次数
		this.timeout=60000;//心跳时间
		this.timeoutObj=null;//心跳对象
		this.serverTimeoutObj=null;//服务器断网对象
		this.lockReconnect = false; //避免重复连接
		this.socket=null;
		this.url=url;
		this.isSupport=typeof(WebSocket) != "undefined";
		if(!this.isSupport){
          
   
			alert("你的浏览器不支持此功能,请使用最新版本的谷歌、火狐浏览器!");
		}else if(isAutoConnect){
          
   
			console.log("自动打开websocket");
			this.init(receiveMsgFun);
		}else{
          
   
			console.log("需要手动打开websocket");
		}
	}

在构造函数在增加一个参数 clearConnFun ,这个参数就是彻底断开后要执行的方法。

修改重连函数

reconnect(receiveMsgFun){
          
   
  	if(this.lockReconnect){
          
   
  		return;
  	}
  	this.lockReconnect=true;
  	this.reconnectNum++;
  	if(this.reconnectNum>this.reconnectTotalNum){
          
   
  		this.reset();
  		console.log("重连次数超过了,不在发起重连请求:"+this.reconnectNum+"-->"+new Date().formatDate("yyyy-MM-dd hh:mm:ss"));
  		 if(this.isFunction(this.clearConnFun)){
          
   
  		 	this.clearConnFun();
  		 }
  		return; 
  	}
  	var $this=this;
  	//没连接上会一直重连,设置延迟避免请求过多
  	setTimeout(function() {
          
   
  		 $this.init(receiveMsgFun);
  		 console.info($this.reconnectNum+正在重连...+new Date().formatDate("yyyy-MM-dd hh:mm:ss"));
  	        $this.lockReconnect = false;
  	 	}, 3000); //这里设置重连间隔(ms)
  }

修改这2处即可实现当彻底断开连接后想要触发的操作。

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket</title>
    <script src="http://127.0.0.1/socket/jquery.min.js"></script>
    <script src="http://127.0.0.1/socket/hn.websocket.min.js"></script>
</head>
<body>
<h3>hello socket</h3>
<p>【fromId】:<div><input id="fromId" name="fromId" type="text" value="google"></div>
<p>【toId】:<div><input id="toId" name="toId" type="text" value="firefox"></div>
<p>【内容】:<div><textarea id="content" name="content"  style="width:400px;height:200px;"></textarea></div>
<p>【操作】:<input type="button" id="open" value="开启socket" />
<p>【操作】:<input type="button" id="sendMsg" value="发送消息" />
<ul id="cont"></ul>
</body>
<script type="text/javascript">
    $(function(){
            
     
    	var socket =null;
    	$("#open").click(function(){
            
     
             var fromId = $("#fromId").val();
       	var socketUrl="ws://127.0.0.1/socketweb/webSocket/"+fromId;
       	socket = new HnWebSocket(socketUrl,true,receiveMsgFun,5,clearConnFun);
       });
       $("#sendMsg").click(function(){
            
     
       	var fromId = $("#fromId").val();
       	var toId = $("#toId").val();
       	var content =  $("#content").val();
             var messageJson ={
            
     fromId:fromId,toId:toId,content:content}
       	socket.sendMessage(JSON.stringify(messageJson));
       });
    })
	function receiveMsgFun(message){
            
     
		$("#cont").append("["+message.createDateTime+"]"+message.content +"<br>");
	}
	//彻底断开后触发的函数
	function clearConnFun(){
            
     
		console.log("彻底断开了");
		alert("彻底断开了");
	}
    </script>
</html>

效果 文件下载: https://download..net/download/zhuiyue82/86500113

经验分享 程序员 微信小程序 职场和发展