{{redata1...._vue集成websocket">
赞
踩
1. vue结合websocket
本人首先是写java后端的,我也是第一次接触websocekt,当然前端也接触的也少,但是楼主已经默默的学会了flex布局,下面的是做的测试页面,写的不好还请谅解。下面时本人总结的websocket可以直接复制拿去用,当然这里说的是前端。这里后端用的netty,后端就不贴源码了,怕被同事看到。项目用的是诺伊框架,
2.上干货 前端websocket
<template>
<div class="test">
{{redata1.userId}}
</div>
</template>
<script>
export default {
name : 'test',
data() {
return {
websock: null,
timer:undefined,
redata1:{
userId:undefined
},
dataping:{
heartbeat:"心跳"
},
sendform:{
userId:"123456"
}
}
},
created() {
if(window.WebSocket){
this.websock = new WebSocket("ws://127.0.0.1:58080/webSocket");
this.initWebSocket();
}else{
alert("浏览器不支持websocket")
}
},
destroyed() {
clearInterval(this.timer)
this.websock.close() //离开路由之后断开websocket连接
},
mounted(){
// const timer = setInterval(()=>{
// // 这里调用调用需要执行的方法,1为自定义的参数,由于特殊的需求它将用来区分,定时器调用和手工调用,然后执行不同的业务逻辑
// this.websocketonopen();
// }, 3000) // 每两秒执行1次
},
methods: {
initWebSocket(){ //初始化weosocket
console.log(this.websock)
this.websock.onmessage = this.websocketonmessage;
this.websock.onopen = this.websocketonopen;
this.websock.onerror = this.websocketonerror;
this.websock.onclose = this.websocketclose;
},
websocketonopen(){ //连接建立之后执行send方法发送数据
let actions = this.sendform
this.websocketsend(JSON.stringify(actions));
this.sendPing();
},
sendPing(){
this.timer = setInterval(()=>{
let actions = this.dataping
this.websock.send(JSON.stringify(actions));
},5000)
},
websocketonerror(){//连接建立失败重连
this.initWebSocket();
},
websocketonmessage(e){ //数据接收
if(e.data=="心跳连接存在"||e.data=="服务器连接成功"){
console.log(e.data)
}else{
this.redata1 = JSON.parse(e.data)
console.log("11111111111---------"+this.redata1.userId)
}
},
websocketsend(Data){//数据发送
this.websock.send(Data);
},
websocketclose(e){ //关闭
console.log('断开连接',e);
},
},
}
</script>
<style scoped lang="scss">
.test{
height: calc(100vh - 84px);
width: 100%;
display: flex;
}
</style>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。