1. 引用 reconnecting-websocket.js
npm i reconnecting- websocket
2. 建立websocket.ts
import ReconnectingWebSocket from 'reconnecting-websocket' ;
let rws: any = null ;
let globalCallback: any = null ;
const initWebsocket = ( ) => {
let url = "ws://localhost:3001" ;
rws = new ReconnectingWebSocket ( url) ;
rws. addEventListener ( "open" , ( ) => {
if ( ! rws) return ;
if ( rws. readyState === 1 ) {
webSocketOpen ( ) ;
}
} ) ;
rws. addEventListener ( "message" , ( e: any ) => {
webSocketOnMessage ( e. data) ;
} ) ;
rws. addEventListener ( "error" , ( e: any ) => {
console . error ( e. message) ;
} ) ;
rws. addEventListener ( "close" , ( ) => {
webSocketClose ( ) ;
} ) ;
}
const webSocketOpen = ( ) => {
console . log ( "建立成功,发送消息" ) ;
let token: any = localStorage. getItem ( 'tokenkey' ) ;
if ( ! isNullOrUndefined ( token) ) {
let obj = {
kind: 1 ,
token: token,
id: 0
}
sendSock ( obj, ( ) => { } ) ;
}
}
const webSocketOnMessage = ( data: any ) => {
globalCallback ( data) ;
}
const webSocketSend = ( data: object) => {
rws. send ( data) ;
}
const webSocketClose = ( ) => {
rws. close ( ) ;
console . log ( "对话连接已关闭" ) ;
}
const sendSock = ( agentData: any , callback: any ) => {
console . log ( "重新连接" )
globalCallback = callback;
console . log ( "rws.readyState" , rws) ;
switch ( rws. readyState) {
case rws. OPEN :
console . log ( "OPEN" )
webSocketSend ( agentData) ;
break ;
case rws. CONNECTING :
console . log ( "CONNECTING" , callback)
setTimeout ( function ( ) {
webSocketSend ( agentData, callback) ;
} , 1000 ) ;
break ;
case rws. CLOSING :
console . log ( "CLOSING" )
setTimeout ( ( ) => {
webSocketSend ( agentData, callback) ;
} , 1000 ) ;
break ;
case rws. CLOSED :
console . log ( "CLOSED" )
break ;
default :
console . log ( "default" )
break ;
}
}
export { initWebsocket, webSocketClose, sendSock } ;
3. 页面使用
import * as socketApi from '@/utils/websocket'
socketApi. sendSock ( '发送的数据' , ( e: any ) => {
console . log ( "后台发送过来的数据" , e)
} )