Js WebSocket类,收发Json,带心跳,断线重连

如题

心跳:4秒发一次

断线:2秒后自动重连

收发:发送和返回json,处理粘包断包等情况,json字符串最大长度9999

缓存:未连接时,自动缓存100个包,当连接时会自动发出

JS代码

js 复制代码
var MyWebSocket = {
	ws : null,
	isConnected : false,
	
	strLast : "",
	
	isDebug : true,
	
	url : "",
	
	//ms
	reconnectTimeout : 2000,
	
	sendBuffMaxSize : 100,
	arrSendBuff : [],
	
	timer : 0,
	
	connect : function(url)
	{
		this.url = url;
		
		var that = this;
		
		if( this.ws != null )
		{
			this.ws.onopen = null;
			this.ws.onmessage = null;
			this.ws.onclose = null;
			this.ws.onerror = null;
		}
		
		if( this.timer==0 )
		{
			timer = setInterval( this.heart, 4000, this );
		}
		
		this.ws = new WebSocket(url);
		
		this.ws.onopen = function()
		{
			that.isConnected = true;
			
		  //当WebSocket创建成功时,触发onopen事件
			that.log("open");
		  
			that.ws.send("0002{}"); //将消息发送到服务端
		
			that.sendBuffJson();
		}
		
		this.ws.onmessage = function(e)
		{
		  that.log(e.data);
		
			that.strLast += e.data;
			
			var strlen = that.strLast.length;
			if( strlen > 4 )
			{
				var len = parseInt( "0x" + that.strLast.substr(0, 4));
				if( len+4 <= strlen )
				{
					var s = that.strLast.substr(4, len+4);
					
					that.strLast = that.strLast.substr(len+4);
					
					that.log("msg come");
					that.log(s);
					
					if( that.onMsgCome != null )
					{
						this.onMsgCome(JSON.parse(s));
					}
				}
			}
		}
		this.ws.onclose = function(e)
		{
		  //当客户端收到服务端发送的关闭连接请求时,触发onclose事件
		  that.log("close");
		
			that.isConnected = false;
			
			that.reconnect();
		}
		this.ws.onerror = function(e){
		  //如果出现连接、处理、接收、发送数据失败的时候触发onerror事件
		  that.log(error);
		}
	},
	
	reconnect : function()
	{
		if( this.reconnectTimeout > 0 )
		{
			setTimeout(this.doReconnect, this.reconnectTimeout, this);
		}
		else this.doReconnect(this);
	},
	
	doReconnect : function(that)
	{
		that.connect(that.url);
	},
	
	sendBuffJson : function()
	{
		var len = this.arrSendBuff.length;
		for( var i=0; i<len; i++ )
		{
			var json = this.arrSendBuff[i];
			
			this.send(json);
		}
		return len;
	},
	
	heart : function(that)
	{
		if( !that.isConnected ) return;
		
		that.timerNum++;
		if( that.timerNum > that.sendNum )
		{
			that.log("heart");
			that.ws.send("0000");
		}
	},
	
	timerNum : 1,
	sendNum : 1,
	
	send : function(json)
	{
		if( !this.isConnected )
		{
			if( this.arrSendBuff.length < this.sendBuffMaxSize )
			{
				this.arrSendBuff.push(json);
			}
			
			return;
		}
		
		this.sendNum = this.timerNum + 1;
		
		var s = JSON.stringify(json);
		
		var prev = "0000" + s.length.toString(16);
		prev = prev.substr(prev.length-4);
		
		s = prev + s;
		
		this.ws.send(s);
	},
	
	log : function(s)
	{
		if( this.isDebug ) console.log(s);
	},
	
	//信息回调回调函数
	onMsgCome : null,
}

测试代码

html 复制代码
<!DOCTYPE html>
<html>
<head>
	<meta charset=utf-8 />
	<title>MyWebSocket</title>
</head>
<script type="text/javascript"> 

</script>
<body>
	<script src="MyWebSocket.js"></script>

	<script>
		var mw = Object.create(MyWebSocket);
		mw.connect("ws://127.0.0.1:8888");
		
		mw.onMsgCome = function(json)
		{
			console.log(json);
		}
		
		setInterval(xx, 3000);
		
		function xx()
		{
			var json = {};
			json.url = "xx";
			json.data = {};
			mw.send(json);
		}
	</script>

</body>

</html>
相关推荐
谢亮_vipxieliang26 分钟前
深入理解 JavaScript 数据类型与类型转换
开发语言·javascript·ecmascript
程序员Sunday10 小时前
JavaScript 事件循环面试题,宏任务与微任务怎么执行|Sunday面试指南
开发语言·javascript·面试·校招·事件循环·程序员sunday
默_笙11 小时前
🌊 向量库和 ES 都查不出"关系",我只好给奶茶建了一张人脉网
前端·javascript
胖头鱼的鱼缸(尹海文)12 小时前
胖头鱼的技术专栏-474 从能跑到能上线:PG SplitJSON 0.2.0 和 0.1.0 差在哪(20261008)
postgresql·json
思无邪6612 小时前
用 AI 做 JS 逆向:从抓包到复现的完整方法论
开发语言·javascript·人工智能
Knight_AL13 小时前
基于 Netty 实现的 WebSocket 服务端
网络·websocket·网络协议
福兮说13 小时前
浏览器里把 iPhone 的 HEIC 转成 JPG:Chrome 解不开、转完大了七成、拍摄时间全丢,六个坑实测
前端·javascript·图像处理·chrome·ios·iphone·heic
可乐鸡翅yeah_14 小时前
video.js 集成 hls.js 开发 M3U8 播放器,新手高频踩坑
开发语言·前端·javascript·后端·ecmascript·m3u8·音视频在线播放
用户1179536547816 小时前
TRAE vs Claude Code 性能对比:从代码生成、多文件重构到底层吞吐,谁更适合你的日常开发?
javascript
?? Daisy17 小时前
Claude Code 接入 GPT:settings.json 两种配置方法(2026-10)
gpt·json