开发websocket应用,最难处理的就是断线后的自动重连
现在GOFLY在线客服使用reconnect-websocket.js就可以非常简单轻松的实现断线重连
reconnect-websocket.js的机制是,当连接websocket服务的过程中,如果连不上,会自动进行指定次数的重试
如果连接成功后回调onOpen方法以后,会把重试次数清空,因此如果是连接已经成功,但是后端主动关闭连接,这个库会不断的进行连接
这个问题也一并处理了下
核心代码在下面,是cdn引入的vue以及element-ui ,GOFLY也是这样的前端架构
<html>
<head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width,initial-scale=1.0" /><!-- Import style --><linkrel="stylesheet"href="https://cdn.jsdelivr.net/npm/element-plus/dist/index.css"/><!-- Import Vue 3 --><script src="https://cdn.jsdelivr.net/npm/vue@next"></script><!-- Import component library --><script src="https://cdn.jsdelivr.net/npm/element-plus"></script>
</head>
<body>
<div id="app"><el-button>${ message }</el-button>
</div>
<script src="../../js/reconnect-websocket.js"></script>
<script>const App = {compilerOptions: {delimiters: ['${', '}'],comments: true},data() {return {message: "Hello Element Plus",apiHost:"ws://gofly.sopans.com/ws_visitor?visitor_id=efccd385-cdfe-41ed-8dfd-ab1faa732996&to_id=taoshihan",websocket:null,websocketOpenNum:0,websocketMaxOpenNum:20,websocketClosed:true,};},methods: {//初始化websocket连接initWebsocketConn() {this.websocket = new ReconnectingWebSocket(this.apiHost,null,{debug:true});//创建Socket实例this.websocket.onmessage = this.onMessage;this.websocket.onopen = this.onOpen;this.websocket.onerror = this.onError;this.websocket.onclose = this.onClose;},onOpen(){console.log("ws:onOpen");if(this.websocketOpenNum>=this.websocketMaxOpenNum){this.websocket.close();}this.websocketOpenNum++;this.websocketClosed=false;this.ping();},onMessage(){console.log("ws:onMessage");},onError(){console.log("ws:onError");},onClose(){console.log("ws:onClose");this.websocketClosed=true;},//心跳包ping(){var _this=this;setInterval(function () {if(!_this.websocketClosed){_this.websocket.send("ping");}},10000);},},//属性初始化created(){this.initWebsocketConn();}};const app = Vue.createApp(App);app.use(ElementPlus);app.mount("#app");
</script>
</body>
</html>