websocket在连接的时候 , 受网络影响

或者长时间没有通信被服务端关闭 , 都需要断线重连机制

 

自己写断线重连比较麻烦 , 可以使用这个js库 ReconnectingWebSocket.js

 https://github.com/joewalnes/reconnecting-websocket/    直接下载min文件 , 引入就可以

使用的时候只需要把h5的原生websocket 替换成 ReconnectingWebSocket , 其他一切照旧

比如: 这是在vue中使用 this.socket就是全局的ReconnectingWebSocket对象 , 其他回调函数也是定义到vue的method上了

            this.socket = new ReconnectingWebSocket("xxxxxx");//创建Socket实例
            this.socket.debug = true;
            this.socket.timeoutInterval = 10000;//连接超时时间
            this.socket.reconnectInterval=5000;//重连间隔时间
            this.socket.maxReconnectInterval = 600000;//最大重连间隔时间
            this.socket.maxReconnectAttempts = 10;//最大重连尝试次数
            this.socket.onmessage = this.OnMessage;
            this.socket.onopen = this.OnOpen;
            this.socket.onerror = this.OnError;
            this.socket.onclose = this.OnClose;

[javascript] js websocket断线重连库ReconnectingWebSocket_JavaScript

 

 超过一分钟没有任何通信 , 会中断 , 然后自动重连