1.封装websoket
var ws = null ;
var lockReconnect = false ;
var timeout = 6 * 1000 * 5 ;
var timeoutObj = null ;
var serverTimeoutObj = null ;
var timeoutnum = null ;
var global_callback = null ;
var openId = localStorage. getItem ( 'openId' )
export function createWebscoket ( uri, callback ) { global_callback = callbackws = new WebSocket ( uri) ws. onopen = ( ) => { lockReconnect = true ws. send ( JSON . stringify ( { "userId" : openId, "toUserId" : openId, "msgType" : 0 } ) ) ; start ( ) } ws. onmessage = onMessagews. onerror = onErrorws. onsend = onSend
}
export function onSend ( message ) { console. log ( ` 发送消息: ${ message} ` ) console. log ( ws. readyState) if ( ws. readyState != 1 ) { reset ( ) } else { ws. send ( message) } }
export function onMessage ( res ) { let msgData = res ? res. data : { } if ( typeof msgData != 'object' && msgData != 'Connect success' ) { var data = msgData. replace ( / \ufeff / g , "" ) ; var message = JSON . parse ( data) global_callback ( message) reset ( ) } }
export function onError ( ) { console. log ( '连接失败' ) ws. close ( ) ws = null lockReconnect = false
}
export function onClose ( ) { console. log ( '连接关闭' )
}
export function closeWs ( ) { if ( lockReconnect) { ws. close ( ) ws = null lockReconnect = false }
}
export function start ( ) { timeoutObj && clearTimeout ( timeoutObj) ; serverTimeoutObj && clearTimeout ( serverTimeoutObj) ; timeoutObj = setTimeout ( function ( ) { if ( ws. readyState == 1 ) { ws. send ( JSON . stringify ( { "userId" : openId, "toUserId" : openId, "msgType" : 0 } ) ) ; } else { reconnect ( ) } serverTimeoutObj = setTimeout ( function ( ) { ws. close ( ) ; } , timeout) ; } , timeout + 3000 )
}
export function reset ( ) { var that = this ; clearTimeout ( timeoutObj) ; clearTimeout ( serverTimeoutObj) ; start ( ) ;
}
export function reconnect ( ) { if ( lockReconnect) { return ; } ; lockReconnect = true ; timeoutnum && clearTimeout ( timeoutnum) ; timeoutnum = setTimeout ( function ( ) { createWebscoket ( ) ; lockReconnect = false ; } , 5000 ) ;
}
2.页面调用
import { createWebscoket, onSend, closeWs, start } from '@/utils/socket.js'
onMounted ( ( ) => { let host = process. env. VUE_APP_WS_HOST createWebscoket ( host + token. value, messagesCallBack) } )
const messagesCallBack = ( msg ) => { console. log ( msg)
}
const closeWsTxt = ( ) => { closeWs ( )
}
const sendMessagext = ( data ) => { onSend ( JSON . stringify ( data) )
}