Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,9 @@ export declare class NUClearNet {
/** Emitted when NUClearNet receives any packet */
public on(event: 'nuclear_packet', callback: (packet: NUClearNetMaybeTypedPacket) => void): this;

/** Emitted when connection to the network is lost */
public on(event: 'disconnect', callback: () => void): this;

/** Emitted when the given packet is received */
public on(event: string, callback: (packet: NUClearNetTypedPacket) => void): this;

Expand Down
20 changes: 18 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ class NUClearNet extends EventEmitter {
event !== 'nuclear_packet' &&
event !== 'newListener' &&
event !== 'removeListener' &&
event !== 'disconnect' &&
this.listenerCount(event) === 0
) {
const hash = this._net.hash(event);
Expand All @@ -60,6 +61,7 @@ class NUClearNet extends EventEmitter {
event !== 'nuclear_packet' &&
event !== 'newListener' &&
event !== 'removeListener' &&
event !== 'disconnect' &&
this.listenerCount(event) === 0
) {
// Get our hash and delete it
Expand Down Expand Up @@ -124,7 +126,17 @@ class NUClearNet extends EventEmitter {

// Only process if we're active
if (this._active) {
this._net.process();
try {
this._net.process();
} catch {
// An error occurred during processing, disconnect.
// This needs to check again if this is still active, as multiple
// `_onWait` calls run concurrently, and only the first one to fail
// should disconnect.
if (this._active) {
this.disconnect();
}
}
}

// Sometimes due to weird timing artifacts we run out of these
Expand Down Expand Up @@ -153,18 +165,22 @@ class NUClearNet extends EventEmitter {
const mtu = options.mtu === undefined ? 1500 : options.mtu;

// Connect to the network
this._active = true;
this._net.reset(name, address, port, mtu);

// Run our first "process" to kick things off
this._net.process();

// If the first process is successful we are active
this._active = true;
}

disconnect() {
this.assertNotDestroyed();

this._active = false;
this._net.shutdown();

this.emit('disconnect');
}

send(options) {
Expand Down