Websocket使用——Vue使用websocket
逻辑实现
- 首先需要判断浏览器是否支持websocket,关于如何解决兼容性问题可以参考:https://juejin.cn/post/6844903602528469005
- 在组件加载的时候连接websocket,在组件销毁的时候断开websocket
- 后端接口需要引入socket模块,否则不能实现连接
代码实例
<script> export default { data () { return { wsUrl: 'ws://127.0.0.1:8551/websocket/yunkuangjian', upgradeSocket: null, lockReconnet: false, //避免重复连接 isReconnet: false, globalCallback: null, } }, created() { //开启socket监控 this.initUpgradeSocket(); }, destroyed: function () { //销毁socket this.socketClose(); }, methods: { //初始化websocket initUpgradeSocket() { if (typeof WebSocket === 'undefined') { alert('您的浏览器不支持socket'); } else { if ('WebSocket' in window) { this.upgradeSocket = new WebSocket(this.wsUrl); } else if ('MozWebSocket' in window) { this.upgradeSocket = new MozWebSocket(this.wsUrl); } // 监听socket连接 this.upgradeSocket.onopen = this.socketOpen; // 监听socket消息 this.upgradeSocket.onmessage = this.socketMessage; // 监听socket错误信息 this.upgradeSocket.onerror = this.socketError; //断开连接 this.upgradeSocket.onclose = this.socketClose; } }, socketOpen() { console.log('socket连接成功'); //heartCheck.reset().start() //后端说暂时不需要做心跳检测 if (this.isReconnet) { //执行全局回调函数 console.log('websocket重新连接了'); // sendMsg(sendData, globalCallback); // isReconnet = false; } }, /** * 接收数据 * @param {} ev */ socketMessage(ev) { const notifyData = ev.data; this.$message(notifyData); //heartCheck.reset().start() //后端说暂时不需要做心跳检测 }, socketError() { console.log('websocket服务出错了---onerror'); }, socketClose() { this.upgradeSocket.close(); console.log('websocket服务关闭了+++onclose'); } }, }