@@ -44,6 +44,7 @@ class NUClearNet extends EventEmitter {
4444 event !== 'nuclear_packet' &&
4545 event !== 'newListener' &&
4646 event !== 'removeListener' &&
47+ event !== 'disconnect' &&
4748 this . listenerCount ( event ) === 0
4849 ) {
4950 const hash = this . _net . hash ( event ) ;
@@ -60,6 +61,7 @@ class NUClearNet extends EventEmitter {
6061 event !== 'nuclear_packet' &&
6162 event !== 'newListener' &&
6263 event !== 'removeListener' &&
64+ event !== 'disconnect' &&
6365 this . listenerCount ( event ) === 0
6466 ) {
6567 // Get our hash and delete it
@@ -124,7 +126,17 @@ class NUClearNet extends EventEmitter {
124126
125127 // Only process if we're active
126128 if ( this . _active ) {
127- this . _net . process ( ) ;
129+ try {
130+ this . _net . process ( ) ;
131+ } catch {
132+ // An error occurred during processing, disconnect.
133+ // This needs to check again if this is still active, as multiple
134+ // `_onWait` calls run concurrently, and only the first one to fail
135+ // should disconnect.
136+ if ( this . _active ) {
137+ this . disconnect ( ) ;
138+ }
139+ }
128140 }
129141
130142 // Sometimes due to weird timing artifacts we run out of these
@@ -153,18 +165,22 @@ class NUClearNet extends EventEmitter {
153165 const mtu = options . mtu === undefined ? 1500 : options . mtu ;
154166
155167 // Connect to the network
156- this . _active = true ;
157168 this . _net . reset ( name , address , port , mtu ) ;
158169
159170 // Run our first "process" to kick things off
160171 this . _net . process ( ) ;
172+
173+ // If the first process is successful we are active
174+ this . _active = true ;
161175 }
162176
163177 disconnect ( ) {
164178 this . assertNotDestroyed ( ) ;
165179
166180 this . _active = false ;
167181 this . _net . shutdown ( ) ;
182+
183+ this . emit ( 'disconnect' ) ;
168184 }
169185
170186 send ( options ) {
0 commit comments