import * as net from "net" ; import IStream from "../../mmocore/IStream" ; export default class NetSocket implements IStream { private _socket ! : net . Socket ; private timeoutTimer ! : ReturnType < typeof setTimeout > ; private timeout = 5000 ; constructor ( private ip , private port ) { } connect ( ) { this . _socket = new net . Socket ( ) ; return new Promise ( ( resolve , reject ) => { this . timeoutTimer = setTimeout ( ( ) => { this . _socket . end ( ) ; this . _socket . destroy ( ) ; reject ( "Socket timeout" ) ; } , this . timeout ) ; this . _socket . setTimeout ( 0 ) ; this . _socket . on ( "error" , ( err ) => reject ( err ) ) ; this . _socket . connect ( this . port , this . ip , ( ) => { clearTimeout ( this . timeoutTimer ) ; resolve ( ) ; } ) ; } ) ; } send ( bytes ) { return new Promise ( ( resolve , reject ) => { if ( ! this . _socket . destroyed ) { if ( this . _socket . write ( bytes ) ) { resolve ( ) ; } else { reject ( "Data not sent" ) ; } } else { reject ( "Connection is closed" ) ; } } ) ; } recv ( ) { this . _socket . resume ( ) ; return new Promise ( ( resolve ) => { this . _socket . once ( "data" , ( data ) => { resolve ( data ) ; this . _socket . pause ( ) ; } ) ; } ) ; } close ( ) { return new Promise ( ( resolve , reject ) => { if ( ! this . _socket . destroyed ) { this . _socket . once ( "close" , ( err ) => { if ( err ) { reject ( err ) ; } else { resolve ( ) ; } } ) ; this . _socket . destroy ( ) ; } } ) ; } toString ( ) { return `${ this . ip }:${ this . port }` ; } }