@@ -9,43 +9,58 @@ const PeerComms = require('./peer-comms')
99
1010
1111class I2pStreamShim extends EventEmitter {
12- constructor ( conn ) {
12+ constructor ( stream ) {
1313 super ( )
14- this . conn = conn
14+ this . stream = stream
1515
16- this . conn . onmessage = ( evt ) => {
17- this . emit ( 'data' , evt . data )
18- }
19-
20- this . conn . onopen = ( ) => {
16+ this . stream . on ( 'data' , data => {
17+ this . emit ( 'data' , data )
18+ } )
19+
20+ this . stream . on ( 'error' , err => {
21+ this . emit ( 'error' , err )
22+ } )
23+
24+ this . stream . once ( 'close' , ( ) => {
25+ this . _isConnected = false
26+ this . emit ( 'close' )
27+ } )
28+
29+ this . stream . once ( 'stream' , ( ) => {
30+ this . _isConnected = true
2131 debugShim ( 'shim open' )
2232 setTimeout ( ( ) => { this . emit ( 'connect' ) } , 1 )
23- }
24-
25- this . conn . onclose = ( ) => {
26- this . emit ( 'close' )
27- }
28-
29- this . conn . onerror = ( err ) => {
30- this . emit ( 'error' , err )
31- }
33+ } )
3234
33- if ( this . conn . readyState == WebSocket . OPEN ) {
35+
36+ if ( this . stream . hasStream ) {
37+ this . _isConnected = true
38+ debugShim ( 'has stream' )
3439 setTimeout ( ( ) => { this . emit ( 'connect' ) } , 1 )
3540 }
41+ }
42+
43+ get isConnected ( ) {
44+ return this . _isConnected
45+ }
3646
37- debugShim ( 'connection shim' , this . conn . readyState )
47+ async connect ( ) {
48+ debugShim ( 'connecting to ' , this . stream . destination )
49+ return await this . stream . connect ( )
3850 }
3951
4052 close ( ) {
41- this . conn . close ( )
53+ this . _closed = true
54+ this . stream . close ( )
4255 }
4356
4457 destroy ( ) {
45- this . conn . terminate ( )
58+ if ( ! this . _closed ) {
59+ this . close ( )
60+ }
4661 }
4762
48- send ( val ) { this . conn . send ( val ) }
63+ send ( val ) { this . stream . send ( val ) }
4964
5065}
5166
@@ -88,6 +103,12 @@ class I2pSocketComms extends PeerComms {
88103 }
89104
90105 this . socket = new I2pStreamShim ( this . stream )
106+
107+ if ( ! this . socket . isConnected ) {
108+
109+ await this . socket . connect ( )
110+
111+ }
91112 }
92113}
93114
0 commit comments