import { Transport } from '../transport' ; import { Message } from './Message' ; import { MessageHeader } from './MessageHeader' ; import { Options } from '../Options' ; import { MessageListener } from './MessageListener' ; export class MessageChannel { private active = true ; constructor ( readonly transport , readonly options , readonly listener ) { this . readLoop ( ) ; } private async readLoop ( ) { let message ; do { message = await this . read ( ) ; if ( this . options . debug ) { console . log ( '<<<' , message ) ; } this . listener . newMessage ( message ) ; } while ( this . active ) ; } private async readHeader ( ) { const response = await this . transport . read ( 24 ) ; return MessageHeader . parse ( response , this . options . useChecksum ) ; } private async read ( ) { const header = await this . readHeader ( ) ; let receivedData ; switch ( header . cmd ) { default : { if ( header . length > 0 ) { receivedData = await this . transport . read ( header . length ) ; } } } const message = new Message ( header , receivedData ) ; return message ; } close ( ) { this . active = false ; } async write ( m ) { if ( this . options . debug ) { console . log ( '>>>' , m ) ; } const data = m . header . toDataView ( ) ; await this . transport . write ( data . buffer ) ; if ( m . data ) { await this . transport . write ( m . data . buffer ) ; } } }