vue websocket电脑端前端集成

后端数据用websocket推送数据,前端在大屏左上角模块页面接收,用bus发送到其他模块(总共6个模块页面,从左上模块页面发送到其他5个模块页面)页面 ,数据用于大屏上显示,废话不多说,直接上代码。

eventBus.js文件,放到根目录src ->assets->js文件夹下,eventBus.js文件内容如下:

import Vue from 'vue';
export default new Vue();

在main.js中配置总websocket总地址,main.js文件在/src/main.js文件夹下

Vue.prototype.serverURL = window.globalUrl.VUE_APP_BASE_URL;
Vue.prototype.wsURL = window.globalUrl.VUE_APP_SOCKET_URL;

在config.js文件下设置VUE_APP_BASE_URL和VUE_APP_SOCKET_URL值,config.js文件在/large-screen/public/js/config.js下

window.globalUrl = {
  // dev环境
  VUE_APP_BASE_URL: 'http://xx.xxx.xx.xx:xxxx',
  VUE_APP_SOCKET_URL: 'ws://xxx.xxx.xx.xx:xxxx/socket/wms/dashboard',
}

在左上模块vue文件,left-top.vue文件中<script></script>内

//引入中央事件总线
import bus from '@/assets/js/eventBus'
//websocket请求和http post请求
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';
import qs from "qs"

 在data(){}同级,创建

created() {
   this.initWebSocket();
},
mounted() {
   this.getData()
 },
destroyed() {
this.websock.close(); //离开路由之后断开websocket连接
},
beforeDestroy() {
  this.clearRefreshData()
},

在methods:{}大括号内写以下方法:

       // 初始化weosocket
            initWebSocket() {
                //接收 "右上"模块“设置”发送过来的 “库区”编码
                let storeCode = this.storeCode
                //从main.js拿到统一ws地址wsURL
                // let wsuri = this.wsURL + this.pageSize + '/';
                let wsuri = this.wsURL;
                this.websock = new WebSocket(wsuri) // 这里面的this都指向vue
                this.websock.onmessage = this.websocketonmessage
                this.websock.onclose = this.websocketclose
                this.websock.onopen = this.websocketopen
                this.websock.onerror = this.websocketerror
            },
            websocketopen() { // 连接建立之后执行send方法发送数据
                // console.log('WebSocket连接成功')
                const actions = {
                    // 'ip': this.ip,
                    // 'port': this.port,
                    // 'operate': this.operate
                }
                bus.$on('sendStoreCodeByBus', data => {
                    this.storeCode = data
                    //关闭websocket
                    this.websock.close();
                    //重连websocket
                    this.reconnect()
                })

                //接收 设置模块设置“字体”发送过来的
                // “字体”大小
                // bus.$on('sendFontSizeByBus', data => {
                //     let fontSizeData = data
                //     //通过字体变化更新滚动插件dom关键字key 更新滚动页面
                //     this.scrollKey = fontSizeData
                // })

                // console.log('发送参数', actions)
                setTimeout(() => {
                    this.websocketsend(JSON.stringify(actions))
                }, 500)
            },
            reconnect() {
                //重新连接
                var that = this;
                if (that.lockReconnect) {
                    // 是否真正建立连接
                    return;
                }
                that.lockReconnect = true;
                //没连接上会一直重连,设置延迟避免请求过多
                that.timeoutnum && clearTimeout(that.timeoutnum);
                // 如果到了这里断开重连的倒计时还有值的话就清除掉
                that.timeoutnum = setTimeout(function() {
                    //然后新连接
                    that.initWebSocket();
                    that.lockReconnect = false;
                }, 5000);
            },
            reset() {
                //重置心跳
                var that = this;
                //清除时间(清除内外两个心跳计时)
                clearTimeout(that.timeoutObj);
                clearTimeout(that.serverTimeoutObj);
                //重启心跳
                that.start();
            },
            start() {
                //开启心跳
                var self = this;
                self.timeoutObj && clearTimeout(self.timeoutObj);
                // 如果外层心跳倒计时存在的话,清除掉
                self.serverTimeoutObj && clearTimeout(self.serverTimeoutObj);
                // 如果内层心跳检测倒计时存在的话,清除掉
                self.timeoutObj = setTimeout(function() {
                    // 重新赋值重新发送 进行心跳检测
                    //这里发送一个心跳,后端收到后,返回一个心跳消息,
                    if (self.websock.readyState == 1) {
                        //如果连接正常
                        // self.websock.send("heartCheck");
                    } else {
                        //否则重连
                        self.reconnect();
                    }
                    self.serverTimeoutObj = setTimeout(function() {
                        // 在三秒一次的心跳检测中如果某个值3秒没响应就关掉这次连接
                        //超时关闭
                        self.websock.close();
                    }, self.timeout);
                }, self.timeout);
                // 3s一次
            },
            websocketonmessage(e) { // 数据接收
                const redata = JSON.parse(e.data)
                // console.log('数据内容:{0}', redata)
                if (redata) {

                    //库位产量
                    this.storageCapacity = redata.storageCapacity
                    //今日喂养
                    this.todayFeed = redata.todayFeed
                    //库位作业
                    this.locationJob = redata.locationJob
                    //喂养异常
                    this.feedError = redata.feedError
                    //批次任务
                    this.batchJob = redata.batchJob
                    //堆垛机报警
                    this.stackerReport = redata.stackerReport
                    //初始化图表
                    this.initStorgeCapcityChart()

                    //通过总线发送“今日喂养”
                    bus.$emit('sendTodayFeedByBus', this.todayFeed)
                    //通过总线发送“库位作业”
                    bus.$emit('sendLocationJobByBus', this.locationJob)
                    //通过总线发送“喂养异常”
                    bus.$emit('sendFeedErrorByBus', this.feedError)
                    //通过总线发送“批次任务”
                    bus.$emit('sendBatchJobByBus', this.batchJob)
                    //通过总线发送“堆垛机报警”
                    bus.$emit('sendStackerReportByBus', this.stackerReport)
                } else {
                    //TODO
                    // console.log("=======暂无数据=====")
                }
                this.reset();
            },
            websocketsend(param) { // 数据发送
                // console.log('***数据发送**', param)
                try {
                    // console.log('*****************', this.websock.readyState)
                    this.websock.send(param)
                } catch (err) {
                    // console.log('error', err)
                }
            },
            websocketclose(e) { // 关闭
                // console.log('WebSocket连接关闭', e)
            },
            websocketerror() { // 失败
                // console.log('WebSocket连接失败')
                this.initWebSocket() // 连接建立失败重连
            },
            clearRefreshData() {
                // clearTimeout(this.refreshTimer)
                clearInterval(this.refreshTimer)
                this.refreshTimer = null
            },
            getData() {
                this.optionsStorgeCapcity = {}
                this.initStorgeCapcityChart(this.optionsStorgeCapcity)
                // this.init(this.optObj)
                // currentGET('big6', { companyName: this.companyName }).then(res => {
                //   // console.log('安装计划', res);
                //   if (res.success) {
                //     this.init(res.data)
                //   } else {
                //     this.pageflag = false
                //     this.$Message({
                //       text: res.msg,
                //       type: 'warning'
                //     })
                //   }
                // })
            },
            //初始化图表
            initStorgeCapcityChart(newData) {
                this.optionsStorgeCapcity = {
                    legend: {
                        data: ['入库量', '出库量'],
                        textStyle: {
                            color: '#ffffff'
                        },
                    },
                    grid: {
                        left: 60
                    },
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: { // 坐标轴指示器,坐标轴触发有效
                            type: 'shadow' // 默认为直线,可选为:'line' | 'shadow'
                        }
                    },
                    xAxis: {
                        type: 'value',
                        name: '数量',
                        nameTextStyle: {
                            color: '#ffffff'
                        },
                        axisLabel: {
                            textStyle: {
                                //x轴纵坐标文字颜色
                                color: '#ffffff'
                            },
                            formatter: '{value}'
                        }
                    },
                    yAxis: {
                        type: 'category',
                        inverse: true,
                        data: this.storageCapacity.libraryName,
                        axisLabel: {
                            formatter: function(value) {
                                return '{' + value + '| }\n{value|' + value + '}';
                            },
                            margin: 20,
                            rich: {
                                value: {
                                    lineHeight: 30,
                                    align: 'center'
                                },
                                Sunny: {
                                    height: 40,
                                    align: 'center',
                                },
                                Cloudy: {
                                    height: 40,
                                    align: 'center',
                                },
                                Showers: {
                                    height: 40,
                                    align: 'center',
                                },
                                Showers: {
                                    height: 40,
                                    align: 'center',
                                }
                            }
                        },
                        axisLabel: {
                            textStyle: {
                                //y轴纵坐标文字颜色
                                color: '#ffffff',
                            },
                            inside: false, // 刻度标签是否朝内,默认朝外
                            rotate: 65 // 刻度标签旋转的角度,在类目轴的类目标签显示不下的时候可以通过旋转防止标签之间重叠;旋转的角度从-90度到90度
                        },
                        splitLine: { //网格线
                            lineStyle: {
                                type: 'dotted' //设置网格线类型 dotted:虚线   solid:实线
                            },
                            show: false //隐藏或显示
                        },
                    },
                    series: [{
                            name: '入库量',
                            type: 'bar',
                            label: {
                                show: true
                            },
                            data: this.storageCapacity.inNum,
                            // [150, 105, 110, 90]
                        },
                        {
                            name: '出库量',
                            type: 'bar',
                            label: {
                                show: true
                            },
                            data: this.storageCapacity.outNum
                            // [220, 82, 63, 110]
                        }
                    ]
                }

            }

 以上是接收websocket发送过来的数据,在其他5个模块接收数据,这里就展示5个接受数据模块中的一个模块,代码如下:

在center-top.vue中<script></script>标签内

//引入中央事件总线
import bus from '@/assets/js/eventBus'

在和data(){}同级写

created() {
    //接收“今日喂养”数据
    bus.$on('sendTodayFeedByBus', data => {
    this.todayFeedObj = data
    // this.getData()
    })
},

在data(){}中定义接收的变量

data() {
    return {
        todayFeedObj: [{
            "storeName": "幼虫仓库",
            "feedTotal": 0,
            "feedNum": 0,
            "feedErrorNum": 0,
            "vehicleTotal": 0
            },
        {
            "storeName": "虫卵仓库",
            "feedTotal": 0,
            "feedNum": 0,
            "feedErrorNum": 0,
            "vehicleTotal": 0
        },
        {
            "storeName": "六天成虫仓库",
            "feedTotal": 0,
            "feedNum": 0,
            "feedErrorNum": 0,
            "vehicleTotal": 0
        },
        {
            "storeName": "二十天成虫仓库",
            "feedTotal": 0,
            "feedNum": 0,
            "feedErrorNum": 0,
            "vehicleTotal": 0
        }
        ],
    };
},    

 数据刷起来:

 

posted @ 2024-04-07 15:58  爱粉刷的小星星  阅读(8)  评论(0编辑  收藏  举报