+
95
-

websocket如何实现断线自动重连?

websocket如何实现断线自动重连?

网友回复

+
15
-

以下是vue版本的一个websocket重连机制,代码如下:

<!DOCTYPE html>

<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum=1.0,minimum=1.0,user-scalable=0" />

    <script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/vue@2.6.1.js"></script>


</head>

<body>
    <div id="app">



    </div>
    <script>
        let websock = null;
        let socketTimer = null;
        let socketParam = {
          type: 'test'
        };
         new Vue({
                el: '#app',
       name: 'test',
      data () {
        return {
          socketUrl: 'ws://web.debug.only.bfw.wiki:9502', 
          timerWS: null, // 用于ws重连
          timerCountWS: 0, // 用于重连计数,0-立刻开始重连,非0-1min重连一次。
          timerFlagWS: true // 跳转页面了不再重连
        }
      },
      mounted () {
        this.initWebsocket()
      },
      destroyed () {
        // 关闭websocket
        this.timerFlagWS = false;
        this.timerCountWS = 0;
        clearTimeout(this.timerWS)
        if (websock !== null) {
          websock.close();
          websock = null;
        }
        clearTimeout(socketTimer);
      },
      methods: {
        initWebsocket () {
          if (typeof WebSocket !== 'undefined') {
            this.timerCountWS++;
            // 浏览器支持Websocket通信协议 ...

点击查看剩余70%

+
15
-

jquery版本的websocket断线重连,代码如下:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum=1.0,minimum=1.0,user-scalable=0" />
<script type="text/javascript" src="//repo.bfw.wiki/bfwrepo/js/jquery-3.2.1.min.js"></script>
    <script type="text/javascript">
     $(function() {
	var lockReconnect = false;//避免重复连接
	var ws = null; //WebSocket的引用
	var wsUrl = "web.debug.only.bfw.wiki:9992"; //这个要与后端提供的相同
	//创建WebSocket连接,如果不确定浏览器是否支持,可以使用socket.js做连接
	function createWebSocket(url){
		 try {
			 if ('WebSocket' in window) {
		        ws = new WebSocket("ws://" + url + "/socketServer");
		     } else {
		        ws = new SockJS("http://" + url + "/sockjs/socketServer");
		     }
	         initEventHandle();
	     } catch (e) {
	         reconnect(wsUrl);
	     }
	}
	
	function reconnect(url) {
        if(lockReconnect) return;
        lockReconnect = true;
        //没连接上会一直重连,设置延迟避免请求过多
        setTimeout(function () {
            createWebSocket(wsUrl);
            console.log("正在重连,当前时间"+new Date())
            lockReconnect = false;
        }, 5000); //这里设置重连间...

点击查看剩余70%

我知道答案,我要回答