1.websocket.js? ?封装好了,直接在项目中引入使用即可
class jtWebSocket{
//构造函数
constructor() {
this.webSocket = null; //webSocket对象
this.url = null; //webSocket连接的url
this.lastHeartBeat = 0; // 上一次心跳时间
this.connectTimer = null; // 重连定时器
this.isPauseConnet = null; // 是否要暂停连接
}
initWebSocket (url) { // 初始化weosocket
this.url = url
this.webSocket = new WebSocket(this.url)
this.lastHeartBeat = new Date().getTime()
if (this.webSocket) {
this.webSocket.onopen = this.websocketonopen
this.webSocket.onerror = this.websocketonerror
this.webSocket.onclose = this.websocketclose
}
}
websocketonopen () { // 连接建立之后执行send方法发送数据
clearInterval(this.connectTimer)
this.isPauseConnet = true
this.connectTimer = null
this.connectTimer = setInterval(this.checkConnect, 5000)
}
// 连接建立失败重连
websocketonerror (callback) {
this.isLoadImg = false
if(this.webSocket&&this.webSocket.readyState){
if (this.webSocket.readyState === 3 || this.webSocket.readyState === 4) {
if (this.isPauseConnet === false) {
this.webSocket = null
}
}
}
callback()
}
// 断开了连接
websocketclose () {
if(this.webSocket&&this.webSocket.readyState){
if (this.webSocket.readyState === 3 || this.webSocket.readyState === 4) {
if (this.isPauseConnet === false) {
this.webSocket = null
}
}
}
}
destroywebsocket () {
// 清除定时器 关闭websocket
this.isPauseConnet = false
clearInterval(this.connectTimer)
this.connectTimer = null
if (this.webSocket) {
this.webSocket.close()
}
}
// 断线重连
checkConnect () {
if (this.connetNum > 3) {
return
}
if ((new Date().getTime() - this.lastHeartBeat) > 8000) {
if (this.webSocket) {
if (this.webSocket.readyState === 3 || this.webSocket.readyState === 4) {
if (this.isPauseConnet === true) {
this.initWebSocket()
this.connetNum++
}
}
} else {
if (this.isPauseConnet === true) {
this.initWebSocket()
this.connetNum++
}
}
} else {
let obj = {
type: 'connect'
}
this.websocketsend(obj)
}
}
// 监听消息
websocketonmessage (callback) {
this.webSocket.onmessage = e =>{
let data = JSON.parse(e.data)
this.lastHeartBeat = new Date().getTime()
if(callback) callback(data)
}
}
// 发送数据
websocketsend (Data) { // 数据发送
if (this.webSocket !== null && this.webSocket.readyState === 1){
this.webSocket.send(JSON.stringify(Data))
}
}
}
export default jtWebSocket
2. 在vue中的使用,目前发的是在vue中的使用,在别的框架里面使用的话需要稍微改下使用方式即可
(1)引入js
import jtWebSocket from "../../service/websocket";
(2)使用
data () {
return {
websocket:null
}
}
methods: {
// 初始化websocket相关
initWebSocket(){
this.websocket = new jtWebSocket()
this.websocket.initWebSocket('ws://127.0.0.1/xxx')
this.websocket.websocketonmessage(data=>{
console.log(data) // 及时通信数据
})
// 连接出错监听
this.websocket.websocketonerror(()=>{
//监听到连接出错后的处理
})
},
// ws 发送消息
handlePostMsg(data){
this.websocket.websocketsend(data)
},
// 断开websocket连接
destroyWs () {
this.websocket.destroywebsocket()
},
}
|