带心跳的websocket

						var wsServer = ws;
						var limitConnect = 5; // 断线重连次数
						var timeConnect = 0;
						webSocketInit(wsServer);
						console.log("websocket地址")
						console.log(ws)
						var codeList = []
						var epcList = []
						var tidList = []
						
						//socket初始化
						function webSocketInit(service) {
							console.log("地址:" + service)
							var ws = new WebSocket(service);
							ws.onopen = function() {
								console.log("已连接TCP服务器");
								var data = {
									type: "heartbeat",
									data: "",
									from: "touchpc"
								}
						
								ws.send(JSON.stringify(data))
							};
							ws.onmessage = function(msg) {
								
								var data = $.parseJSON(msg.data);
								
								if (data.type == "heartbeat") {
						
						
								} else if (data.type == "pushbook") {
									console.log("检索到的数据")
									var result = $.parseJSON(msg.data).data
									
						
						
								}
								
						
							};
						
							ws.onclose = function() {
								console.log('服务器已经断开');
								reconnect(service);
							};
							ws.onerror = function(err) {
								console.log("服务器报错:");
								reconnect(service);
							};
						
							// 重连
							function reconnect(service) {
								// lockReconnect加锁,防止onclose、onerror两次重连
								if (limitConnect > 0) {
									if (localStorage.getItem('lockReconnect') != true) {
										localStorage.setItem("lockReconnect", 1);
										limitConnect--;
										timeConnect++;
										console.log("第" + timeConnect + "次重连");
										// 进行重连
										setTimeout(function() {
											webSocketInit(service);
											localStorage.removeItem("lockReconnect");
										}, 2000);
									}
								} else {
									console.log("TCP连接已超时");
								}
							}
						
							// 心跳 * 回应
							setInterval(function() {
								var data = {
									type: "heartbeat",
									data: "",
									from: "touchpc"
								}
						
								ws.send(JSON.stringify(data))
								// websocket.send(JSON.stringify(data));
							}, 1000 * 100);
						}

上一篇:java 实现websocket当客户端连接服务器以及自动重连的方式


下一篇:体验了一把websocket