mounted(){
this.initSocket()
},
methods:{
initSocket(){
const ip = '127.0.0.1'
const port= '8083'
const username= 'zs'
let url = `ws://${ip}:${port}/xxx/${username}`
this.webSocket = new WebSocket(url)
this.webSocket.onopen = this.webSocketOnOpen
this.webSocket.onclose = this.webSocketOnClose
this.webSocket.onmessage = this.webSocketOnMessage
this.webSocket.onerror = this.webSocketOnError
// 重置下间隔最新时间
this.queryForm.time1 = this.parseTime(new Date())
this.webSocketResend()
},
// 发送数据
wsSend () {
let param={name:'张三'} // 这里可以随意改,反正要string数据类型
this.webSocket.send(JSON.stringify(param))
},
// 接收数据
wsGetData (data) {
// 这里出来接收的数据
},
// 建立连接成功后的状态
webSocketOnOpen() {
console.log('websocket连接成功');
this.wsSend()
},
// webSocketResend重新发送数据-5秒没数据,就更新
webSocketResend(){
let skip = 1*5*1000 // 这里间隔多少秒可以改
let skipTime = 1 *5
this.timerW = setInterval(()=>{
// 间隔秒数
let intervaltime = (new Date().getTime() - new Date(this.queryForm.time1).getTime()) / 1000;
// 大于5秒还没数据,就需要重连
if(intervaltime>skipTime){
// console.log('intervaltime',intervaltime,',skip',skip)
// console.log('webSocket',this.webSocket.readyState )
// 重连
this.webSocketOnClose()
this.initSocket()
}
},skip)
},
// 获取到后台消息的事件,操作数据的代码在onmessage中书写
webSocketOnMessage(res) {
// res就是后台实时传过来的数据
// console.log(res, 'webSocketOnMessage');
let data = JSON.parse(res.data)
this.wsGetData(data)
//给后台发送数据
// this.webSocket.send("发送数据");
},
// 关闭连接
webSocketOnClose() {
this.webSocket.close()
console.log('websocket连接已关闭');
},
//连接失败的事件
webSocketOnError(res) {
console.log('websocket连接失败');
// 打印失败的数据
console.log(res);
},
},
vue 连接websocket,及5秒之后没有数据,就关闭上一个,重新连接ws
猜你喜欢
转载自blog.csdn.net/qq_26841153/article/details/131232101
今日推荐
周排行