原生websocket实现断线重连
1、原生websocket实现断线重连
export default { name: "sideBar", components: { // viewImage, svgIcon, }, props: {}, data() { return { sock: null, url: "wss://xxx.com/t-go-wss/ws", }; }, mounted() {this.createWebSocket(this.url); }, beforeUnmount() { this.sock.close(); }, methods: { reconnect() { let _this = this; setTimeout(function () { _this.createWebSocket(this.url); }, 500); }, initWebSocket() { let _this = this; this.sock.onopen = function () { console.log("open"); _this.sock.send( JSON.stringify({ topicType: "orderSuc", dataType: "orderPrint", firmCode: "gojingping", }) ); }; this.sock.onmessage = function (e) { console.log("message", e.data); if (e.data) { _this.$refs.audio.load(); _this.$refs.audio.play(); } }; this.sock.onclose = function () { console.log("close"); _this.reconnect(); }; this.sock.onerror = function () { console.log("onerror"); _this.reconnect(); }; }, createWebSocket(url) { try { if ("WebSocket" in window) { this.sock = new WebSocket(url); } else { alert("当前浏览器不支持websocket协议,建议使用现代浏览器"); return; } this.initWebSocket(); } catch (e) { this.reconnect(); } }, }, };

浙公网安备 33010602011771号