Skip to content

Commit 4bdb008

Browse files
authored
Emit disconnect event when network connection is lost (#27)
1 parent fa78596 commit 4bdb008

2 files changed

Lines changed: 21 additions & 2 deletions

File tree

index.d.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,9 @@ export declare class NUClearNet {
140140
/** Emitted when NUClearNet receives any packet */
141141
public on(event: 'nuclear_packet', callback: (packet: NUClearNetMaybeTypedPacket) => void): this;
142142

143+
/** Emitted when connection to the network is lost */
144+
public on(event: 'disconnect', callback: () => void): this;
145+
143146
/** Emitted when the given packet is received */
144147
public on(event: string, callback: (packet: NUClearNetTypedPacket) => void): this;
145148

index.js

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -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

Comments
 (0)