webscoket的简单使用
1、第一步:需要建立一个全局的js文件,我在这里取名为global.js
export default {
ws: {},
setWs: function (newWs) {
this.ws = newWs;
},
};
2、第二部:将刚刚新建的文件夹引入main.js文件中进行全局注册
import gloabl from '@/assets/utils/global';
Vue.prototype.$global = gloabl;
3、在入口文件App.js中去检测浏览器的适应情况
methods: {
localSocket() {
let that = this;
if ('WebSocket' in window) {
that.ws = new WebSocket('ws://192.168.35.20:8872/dashbord');//创建一个实例对象,括号中为你需要监听的地址
that.$global.setWs(that.ws);
that.ws.onopen = function () {//在这里你可以写属于自己的逻辑
console.log('成功建立连接了...');
};
that.ws.onerror = function () {
setTimeout(() => {
that.localSocket();
}, 2000);
};
that.ws.onclose = function () {
console.log('连接已关闭...');
setTimeout(() => {
that.localSocket();
}, 2000);
};
} else {
console.log('您的浏览器不支持 WebSocket!');
}
},
},
created() {
this.localSocket();
},
4、在其它的页面中应用
methods: {
handleMsg() {
let that = this;
//监听websocket接收消息事件(接收来自服务器的实时消息)
that.$global.ws.onmessage = function (res) {
let getObj = JSON.parse(res.data);
if (getObj.type === 'shield') {
that.dataShiedArr = [getObj.message, ...that.dataShiedArr];
that.dataShiedArr = that.dataShiedArr.filter((item) => item);
if (
that.dataShiedArr.length === 1 ||
that.dataShiedArr.length === 2 ||
that.dataShiedArr.length === 3 ||
that.dataShiedArr.length === 4
) {
that.dataShiedArr = ['', '', '', '', '', ...that.dataShiedArr];
}
} else {
that.dataMonitorArr = [getObj.message, ...that.dataMonitorArr];
that.dataMonitorArr = that.dataMonitorArr.filter((item) => item);
if (
that.dataMonitorArr.length === 1 ||
that.dataMonitorArr.length === 2 ||
that.dataMonitorArr.length === 3 ||
that.dataMonitorArr.length === 4
) {
that.dataMonitorArr = ['', '', '', '', '', ...that.dataMonitorArr];
}
}
};
},
},
mounted() {
this.handleMsg();
},
以上为一个简单的webscoket应用,代码可以直接粘贴、复制使用