WebSocket:实时获取数据
在vue中使用
realTimeGetLog(){
var socket;
let that=this
if(typeof(WebSocket) == "undefined") {
console.log("您的浏览器不支持WebSocket");
}else{
//实现化WebSocket对象,指定要连接的服务器地址与端口 建立连接
socket = new WebSocket("ws://192.168.12.50:8080/websocket");
//打开事件
socket.onopen = function() {
console.log("Socket 已打开");
//socket.send("这是来自客户端的消息" + location.href + new Date());
};
//获得消息事件
socket.onmessage = function(msg) {//在此触发事件,dosomething....
console.log(msg.data);
contLog(Object.assign({})).then(res => {
if (res.code == '200') {
that.rizhilist = res.data;
} else {
this.$message.error(res.msg);
}
})
//发现消息进入 开始处理前端触发逻辑
};
//关闭事件
socket.onclose = function() {
console.log("Socket已关闭");
};
//发生了错误事件
socket.onerror = function() {
alert("Socket发生了错误");
//此时可以尝试刷新页面
}
}
},
然后在mounted中调用realTimeGetLog()方法即可,后台弄好后,WebSocket会自动触发