@@ -17,59 +17,62 @@ class WebSocketTransport extends EventEmitter {
1717 this . tries = 0 ;
1818 }
1919
20- async connect ( tries = this . tries ) {
21- if ( this . connected ) {
22- return ;
23- }
24- const port = 6463 + ( tries % 10 ) ;
25- this . hostAndPort = `127.0.0.1:${ port } ` ;
26- const ws = this . ws = new WebSocket (
27- `ws://${ this . hostAndPort } /?v=1&client_id=${ this . client . clientId } ` ,
20+ async connect ( ) {
21+ const port = 6463 + ( this . tries % 10 ) ;
22+ this . tries += 1 ;
23+
24+ this . ws = new WebSocket (
25+ `ws://127.0.0.1:${ port } /?v=1&client_id=${ this . client . clientId } ` ,
2826 {
2927 origin : this . client . options . origin ,
3028 } ,
3129 ) ;
32- ws . onopen = this . onOpen . bind ( this ) ;
33- ws . onclose = ws . onerror = this . onClose . bind ( this ) ;
34- ws . onmessage = this . onMessage . bind ( this ) ;
30+ this . ws . onopen = this . onOpen . bind ( this ) ;
31+ this . ws . onclose = this . onClose . bind ( this ) ;
32+ this . ws . onerror = this . onError . bind ( this ) ;
33+ this . ws . onmessage = this . onMessage . bind ( this ) ;
3534 }
3635
37- send ( data ) {
38- if ( ! this . ws ) {
39- return ;
40- }
41- this . ws . send ( pack ( data ) ) ;
36+ onOpen ( ) {
37+ this . emit ( 'open' ) ;
4238 }
4339
44- close ( ) {
45- if ( ! this . ws ) {
40+ onClose ( event ) {
41+ if ( ! event . wasClean ) {
4642 return ;
4743 }
48- this . ws . close ( ) ;
44+ this . emit ( 'close' , event ) ;
4945 }
5046
51- ping ( ) { } // eslint-disable-line no-empty-function
47+ onError ( event ) {
48+ try {
49+ this . ws . close ( ) ;
50+ } catch { } // eslint-disable-line no-empty
51+
52+ if ( this . tries > 20 ) {
53+ this . emit ( 'error' , event . error ) ;
54+ } else {
55+ setTimeout ( ( ) => {
56+ this . connect ( ) ;
57+ } , 250 ) ;
58+ }
59+ }
5260
5361 onMessage ( event ) {
5462 this . emit ( 'message' , unpack ( event . data ) ) ;
5563 }
5664
57- onOpen ( ) {
58- this . emit ( 'open' ) ;
65+ send ( data ) {
66+ this . ws . send ( pack ( data ) ) ;
5967 }
6068
61- onClose ( e ) {
62- try {
69+ ping ( ) { } // eslint-disable-line no-empty-function
70+
71+ close ( ) {
72+ return new Promise ( ( r ) => {
73+ this . once ( 'close' , r ) ;
6374 this . ws . close ( ) ;
64- } catch ( err ) { } // eslint-disable-line no-empty
65- const derr = e . code >= 4000 && e . code < 5000 ;
66- if ( ! e . code || derr ) {
67- this . emit ( 'close' , e ) ;
68- }
69- if ( ! derr ) {
70- // eslint-disable-next-line no-plusplus
71- setTimeout ( ( ) => this . connect ( e . code === 1006 ? ++ this . tries : 0 ) , 250 ) ;
72- }
75+ } ) ;
7376 }
7477}
7578
0 commit comments