@@ -154,9 +154,8 @@ const addHeaders = ({ origin }) => {
154154 if ( origin ) HEADERS [ 'Access-Control-Allow-Origin' ] = origin ;
155155} ;
156156
157- class Server extends EventEmitter {
157+ class Server {
158158 constructor ( application , options ) {
159- super ( ) ;
160159 this . retry = options . retry ?? DEFAULT_LISTEN_RETRY ;
161160 this . application = application ;
162161 this . options = options ;
@@ -166,20 +165,15 @@ class Server extends EventEmitter {
166165 this . httpServer = null ;
167166 this . wsServer = null ;
168167 this . clients = new Set ( ) ;
169- this . bind ( ) ;
168+ this . init ( ) ;
170169 }
171170
172- bind ( ) {
173- const { application, console, balancer } = this ;
174- const { host, port, protocol, timeouts, nagle = true } = this . options ;
175- const { key, cert, SNICallback } = this . options ;
171+ init ( ) {
172+ const { application, balancer, options } = this ;
173+ const { protocol, nagle = true , key, cert, SNICallback } = options ;
176174 const proto = protocol === 'http' || balancer ? http : https ;
177- const options = { key, cert, noDelay : ! nagle , SNICallback } ;
178- this . httpServer = proto . createServer ( options ) ;
179-
180- this . httpServer . on ( 'listening' , ( ) => {
181- console . info ( `Listen port ${ port } ` ) ;
182- } ) ;
175+ const opt = { key, cert, noDelay : ! nagle , SNICallback } ;
176+ this . httpServer = proto . createServer ( opt ) ;
183177
184178 this . httpServer . on ( 'request' , async ( req , res ) => {
185179 const transport = new HttpTransport ( this , req , res ) ;
@@ -212,18 +206,30 @@ class Server extends EventEmitter {
212206 else this . message ( client , data ) ;
213207 } ) ;
214208 } ) ;
209+ }
215210
216- this . wsServer . on ( 'error' , ( err ) => {
217- if ( err . code !== 'EADDRINUSE' ) return ;
218- this . retry -- ;
219- if ( this . retry === 0 ) return void this . emit ( 'error' , err ) ;
220- console . warn ( `Address in use: ${ host } :${ port } , retry...` ) ;
221- setTimeout ( ( ) => {
222- this . bind ( ) ;
223- } , timeouts . bind ) ;
224- } ) ;
211+ listen ( ) {
212+ const { console, options } = this ;
213+ const { host, port, timeouts } = options ;
225214
226- this . httpServer . listen ( port , host ) ;
215+ return new Promise ( ( resolve , reject ) => {
216+ this . httpServer . on ( 'listening' , ( ) => {
217+ console . info ( `Listen port ${ port } ` ) ;
218+ resolve ( this ) ;
219+ } ) ;
220+
221+ this . wsServer . on ( 'error' , ( err ) => {
222+ if ( err . code !== 'EADDRINUSE' ) return ;
223+ this . retry -- ;
224+ if ( this . retry === 0 ) return void reject ( err ) ;
225+ console . warn ( `Address in use: ${ host } :${ port } , retry...` ) ;
226+ setTimeout ( ( ) => {
227+ this . httpServer . listen ( port , host ) ;
228+ } , timeouts . bind ) ;
229+ } ) ;
230+
231+ this . httpServer . listen ( port , host ) ;
232+ } ) ;
227233 }
228234
229235 message ( client , data ) {
0 commit comments