在vue 项目中使用webscoket 与后台实时通信的使用 需后端提供对应的接口地址
vue项目中的使用方法
data(){
return{
//用户创建连接webscoket
websock:null,
//定时器
timer:null,
}
},
created(){
//初始化websocket
this.initWebSocket();
},
methods:{
//初始化websocket
initWebSocket(){
if (typeof WebSocket === "undefined") return alert("您的浏览器不支持WebSocket")
// websocket地址 其中 "ws" 对应的传输协议 "ws" -->http "wss" -->https
let socketApi = 后端提供的地址 例如 "xxxxxx.com/websocket/ ";
let userId = 1; //和后端协定的 我这项目中是根据用户id进行区分
const wsuri = 'ws://' + socketApi + userId;
// 初始化socket方法
this.websock = new WebSocket(wsuri);
// 连接成功的处理
this.websock.onopen = this.websocketonopen;
// 接收数据之后的处理
this.websock.onmessage = this.websocketonmessage;
// 报错的处理
this.websock.onerror = this.websocketonerror;
// 关闭连接的处理
this.websock.onclose = this.websocketclose;
},
//scoket连接成功
websocketonopen(){
console.log('scoket已连接');
const that= this;
this.timer = setInterval(() => {
try {
// 向服务端标明本机心跳
const jsonHeart = {
status: 'heart',
msg: '心跳'
}
// 发送消息
that.websock.send(JSON.stringify(jsonHeart))
//判断准备状态
if(that.websock.readyState !== 1){
that.initWebSocket()
}
}catch (err) {
that.connection()
}
},6000) //定时发送
},
//接收后端返回的数据
websocketonmessage: async function (e) {
//打印返回的数据 查看数据格式 可以JSON.parse()进行转换
console.log(e)
//根据项目需求完成后续操作
},
//scoket连接失败
websocketonerror(e){
console.log('scoket失败')
console.log(e)
//尝试重新连接
this.initWebSocket();
},
//关闭socket链接
websocketclose(e){
console.log('断开连接' + e)
console.log(e)
this.websock.close()
}
}
webscoket连接成功]打印