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

在上一篇文章里介绍了如何在前端进行websocket封装时,进行断网重连、心跳监测等,在最近梳理的时候发现在断网重连这块少考虑了一块,例如默认情况下,断网后前端会每隔3秒重新与服务器握手一次,共握手5次后还没成功就彻底断开,这在实际项目里就存在问题,例如实际需求中需要一旦超过握手总次数就执行新的功能,例如提示操作者或者将异常入库等。

修改构造函数

/**
	 * 构造函数
	 * @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.youkuaiyun.com/download/zhuiyue82/86500113

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值