import { NodeMessage } from '../NodeMessage' ; import { Queue } from '../Queue' ; import { Socket as NetSocket } from 'net' ; import { create , read } from '../../Util/Header' ; import { serialize } from 'binarytf' ; import { SendOptions } from '../../Util/Shared' ; /**
 * The abstract socket handler for  ClientSocket and  ServerSocket .
 *  since private export abstract class SocketHandler { since public name : string | null ; since public socket : NetSocket ; since public queue = new Queue ( ) ; since param name param socket public constructor ( name , socket ) { this . name = name ; this . socket = socket ; } param data param options public send ( data , options = { } ) { if ( this . socket . destroyed ) { return Promise . reject ( new Error ( 'Cannot send a message to a missing socket.' ) ) ; } const { receptive = true , timeout = - 1 } = options ; return new Promise ( ( resolve , reject ) => { let id ; try { const serialized = serialize ( data ) ; const message = create ( receptive , serialized ) ; id = read ( message ) . id ; this . socket ! . write ( message ) ; if ( ! receptive ) { resolve ( undefined ) ; return ; } const timer = timeout === - 1 ? null : setTimeout ( ( ) => send ( reject , true , new Error ( 'Timed out.' ) ) , timeout ) ; const send = ( fn , fromTimer , response ) => { if ( timer && ! fromTimer ) clearTimeout ( timer ) ; this . queue . delete ( id ) ; return fn ( response ) ; } ; this . queue . set ( id , { resolve : send . bind ( null , resolve , false ) , reject : send . bind ( null , reject , false ) } ) ; } catch ( error ) { const entry = this . queue . get ( id ! ) ; if ( entry ) entry . reject ( error ) ; else reject ( error ) ; } } ) ; } protected _handleMessage ( message ) { const queueData = this . queue . get ( message . id ! ) ; if ( queueData ) { queueData . resolve ( message . data ) ; return null ; } return new NodeMessage ( this , message . id ! , message . receptive , message . data ) . freeze ( ) ; } protected abstract _onData ( data ) ; } since private internal export interface RawMessage { since id : number | null ; since receptive : boolean ; since data : any ; }