import { Component,Vue } from "vue-property-decorator";
import Axios from 'axios'
// 当前长链接的实例
export let wsInstance: WebSocket | null = null
export type StateType = 'connecting' | 'connected' | 'closing' | 'closed'
// 检查长链接状态
export function checkWebSocketState(instan:WebSocket):StateType {
if(!instan)return 'closed'
let state:StateType="closed"
switch(instan.readyState) {
case WebSocket.CONNECTING:
state="connecting"
break;
case WebSocket.OPEN:
state="connected"
break;
case WebSocket.CLOSING:
state="closing"
break;
case WebSocket.CLOSED:
state="closed"
break;
default:
state="closed"
break;
}
return state
}
@Component({
name: 'myWebsocket',
})
export default class MyWebsocket extends Vue {
/** ws 状态 */
stateType:StateType = 'closed'
ws: WebSocket | null = null
token:string=""
changeState(type: StateType) {
this.stateType = type
}
/** 发送保活信息的 setInterval id */
keepAliveId = 0
/** 连接 ws */
async connect() {
let requestUrl=""
return new Promise<void>((resolve, reject) => {
if(this.ws || wsInstance)this.setInitState()
if (this.stateType !== 'closed') throw Error('WS is used!')
const wsPath=requestUrl+"/myws"
this.ws = new WebSocket((location.protocol.split(":")[0]==="http" ? 'ws' : 'wss')+'://'+wsPath)
wsInstance=this.ws
this.changeState('connecting')
let _this = this;
this.ws.onopen = function (event) {
_this.changeState('connected')
// 发送保活信息
// _this.keepAliveId = window.setInterval(() => {
// if (_this.ws && _this.ws.readyState === _this.ws.OPEN) {
// _this.ws.send('0')
// } else {
// window.clearInterval(_this.keepAliveId)
// }
// }, 20 * 1000)
resolve()
}
this.ws.onmessage = function(event) {
let eventData = event.data
try {
eventData = JSON.parse(eventData)
} catch {}
}
this.ws.onclose = function(event) {
// 如果当前还处于连接中,说明初始化ws连接失败
if (_this.stateType === 'connecting') {
reject(Error('ws connect failed!'))
}
_this.ws = null
wsInstance=null
_this.changeState('closed')
}
})
}
sendMessage(params:any){
return new Promise((resolve:Function,reject:Function)=>{
if (this.ws && this.ws.readyState === this.ws.OPEN) {
this.ws.send(JSON.stringify(params))
resolve()
} else{
reject("ws connect failed!")
}
})
}
/** 断开连接 */
disconnect() {
const instan= this.ws || wsInstance
if(instan!==null){
this.ws?.close()
wsInstance?.close()
}
}
setInitState(){
const instan= this.ws || wsInstance
if(instan){
let state:StateType=checkWebSocketState(instan)
if(['closing','closed'].includes(state)){
state="closed"
}
this.changeState(state)
console.log("ws 状态"+this.stateType)
}
}
}
nuxt vue websocket接入
最新推荐文章于 2025-01-15 11:35:41 发布