data(){
return {
socket:null
}
}
mounted() {
// 初始化
this.init()
},
// 组件被销毁时关闭监听,如不关闭,websocket会一直挂载
beforeDestroy() {
this.close()
},
methods: {
// 进入聊天室,连接socket
init: function () {
let that = this
if (typeof WebSocket === 'undefined') {
alert('您的浏览器不支持socket')
} else {
// 实例化socket
this.socket = new WebSocket(你的socket地址)
// 监听socket连接
this.socket.onopen = this.open
// 监听socket错误信息
this.socket.onerror = this.error
// 监听socket消息
this.socket.onmessage = this.getMessage
//关闭 的函数 onclose 并不是关闭函数
this.socket.close = this.close
}
},
open: function () {},
error: function () {
this.init()
},
getMessage: function (msg) {
let that = this
if (msg.data == 'HeartBeat') {
return
}
以下是对数据进行的处理,注意要将传入的对象进行josn解码操作,不然不是对象形式
let str = JSON.parse(msg.data)
if (str.projectId == this.projectId) {
this.newsArr.push(str)
// 滚动
this.$nextTick(() => {
let msg = document.getElementById('gundong') // 获取对象
if (msg == null) {
return
}
msg.scrollTop = msg.scrollHeight // 滚动高度
})
//播放提示音,提示来消息了——
let audio = document.querySelector('#tishi-audio')
audio.play()
}
// 关闭连接
close: function () {
//在其内执行函数,相当于onclose 这个websocket的周期
clearInterval(this.timeoutObj)
},
},
}
websocket 配置 vue
最新推荐文章于 2025-05-29 09:42:37 发布