import WebSocketClinet from "./WebSocketClient" ; import { Message , IMessage } from "./Message" ; description export class ServerConnector { description private _wsClient : WebSocketClinet = null ; constructor ( ) { this . _wsClient = new WebSocketClinet ( ) ; this . _wsClient . onClose = this . onClose . bind ( this ) ; this . _wsClient . onError = this . onError . bind ( this ) ; this . _wsClient . onMessage = this . onMessage . bind ( this ) ; this . _wsClient . onOpen = this . onOpen . bind ( this ) ; } description protected sendHeartbeat ( ) { if ( CC_DEBUG ) cc . error ( `请重写sendHeartbeat` ) ; } description protected getMaxHeartbeatTimeOut ( ) { return 5 ; } description protected getHeartbeatInterval ( ) { return 5000 ; } description protected onHeartbeatTimeOut ( ) { } description protected isHeartBeat ( data ) { return false ; } description protected onOpen ( ) { this . _curRecvHartTimeOutCount = 0 ; this . stopSendHartSchedule ( ) ; this . sendHeartbeat ( ) ; this . startSendHartSchedule ( ) ; } description protected onClose ( ev ) { this . stopSendHartSchedule ( ) ; } description protected onError ( ev ) { this . stopSendHartSchedule ( ) ; } description protected onMessage ( data ) { this . recvHeartbeat ( ) ; } description protected recvHeartbeat ( ) { this . _curRecvHartTimeOutCount = 0 ; } private _sendHartId : number = - 1 ; private _curRecvHartTimeOutCount : number = 0 ; description param ip param port param protocol public connect ( ip , port = null , protocol = "wss" ) { if ( port ) { if ( typeof port == "string" && port . length > 0 ) { this . _wsClient && this . _wsClient . initWebSocket ( ip , port , protocol ) ; } else if ( typeof port == "number" && port > 0 ) { this . _wsClient && this . _wsClient . initWebSocket ( ip , port . toString ( ) , protocol ) ; } else { this . _wsClient && this . _wsClient . initWebSocket ( ip , null , protocol ) ; } } else { this . _wsClient && this . _wsClient . initWebSocket ( ip , null , protocol ) ; } } description private stopSendHartSchedule ( ) { if ( this . _sendHartId != - 1 ) { clearInterval ( this . _sendHartId ) ; this . _sendHartId = - 1 ; } } description private startSendHartSchedule ( ) { let self = this ; this . _sendHartId = setInterval ( ( ) => { self . _curRecvHartTimeOutCount = self . _curRecvHartTimeOutCount + 1 ; if ( self . _curRecvHartTimeOutCount > self . getMaxHeartbeatTimeOut ( ) ) { self . stopSendHartSchedule ( ) ; self . onHeartbeatTimeOut ( ) ; return ; } self . sendHeartbeat ( ) ; } , self . getHeartbeatInterval ( ) ) ; } description param msg protected sendBuffer ( buffer ) { this . _wsClient && this . _wsClient . send ( buffer ) ; } public close ( ) { this . stopSendHartSchedule ( ) ; this . _wsClient && this . _wsClient . close ( ) ; } }