直接上代码
分方法代码-util.ts中
let websock : any = null ;
let global_callback : any = null ;
function createWebSocket ( callback : any, url : any) { if ( websock == null || typeof websock !== WebSocket) { initWebSocket ( callback, url) ; }
}
function initWebSocket ( callback : any, url : any) { global_callback = callback; websock = new WebSocket ( url) ; websock. onmessage = function ( e : any) { websocketonmessage ( e, "0" ) ; } ; websock. onclose = function ( e : any) { websocketclose ( e) ; } ; websock. onerror = function ( ) { console. log ( "WebSocket连接发生错误" ) ; } ;
}
function sendSock ( agentData : any) { if ( websock. readyState === websock. OPEN ) { websocketsend ( agentData) ; } else if ( websock. readyState === websock. CONNECTING ) { setTimeout ( function ( ) { sendSock ( agentData) ; } , 1000 ) ; } else { setTimeout ( function ( ) { sendSock ( agentData) ; } , 1000 ) ; }
}
function websocketonmessage ( msg : any, type) { let result : any = null ; result = msg. data; switch ( type) { case "0" : global_callback ( result) ; break ; default : break ; }
}
function closeSock ( ) { if ( websock) { websock. close ( ) ; }
}
function websocketclose ( e : any) { console. log ( "connection closed (" + e. code + ")" ) ;
} export { sendSock, createWebSocket, closeSock } ;
页面使用
onMounted ( ( ) => { createWebSocket ( ( msg : any) => { mapFlightPositionFun ( msg) ; } , WebSocketUrl1) ;
}
onBeforeUnmount ( ( ) => { closeSock ( ) ;
} const mapFlightPositionFun = Data => { if ( Data !== "连接成功" ) { }
}