import * as net from "net" ; import { NetworkErrorType } from "../core/global" ; import { LoggingHelper } from "../core/logging-helper" ; let Logger = "TCP-CLIENT" ; export interface TCPClientCallback { ( data , errorType , errorMessage ) : void ; } export class TCPClient { public onCloseCallback : ( ) => void ; public constructor ( public id ) { } public transmit ( host , port , requestData , callback ) { let self = this ; let client = new net . Socket ( ) ; LoggingHelper . info ( Logger , "Forwarding " + host + ":" + port ) ; client . on ( "error" , function ( e ) { console . log ( "TCPClient Error: " + e . message ) ; if ( e . code === "ECONNREFUSED" ) { callback ( null , NetworkErrorType . CONNECTION_REFUSED , e . message ) ; } else { callback ( null , NetworkErrorType . OTHER , e . message ) ; } } ) ; client . connect ( port , host , function ( ) { client . write ( requestData ) ; } ) ; client . on ( "data" , function ( incomingData ) { callback ( incomingData , null , null ) ; } ) ; client . on ( "close" , function ( had_error ) { LoggingHelper . debug ( Logger , "Connection closed ID: " + self . id + " HadError: " + had_error ) ; if ( self . onCloseCallback !== undefined && self . onCloseCallback !== null ) { self . onCloseCallback ( ) ; } } ) ; } public close ( ) { } }