diff --git a/src/lib/agent/Peer.mjs b/src/lib/agent/Peer.mjs index a30ec6a..de5f963 100644 --- a/src/lib/agent/Peer.mjs +++ b/src/lib/agent/Peer.mjs @@ -1,6 +1,6 @@ "use strict"; -import { EventEmitter } from 'events'; +import { EventEmitter, once } from 'events'; import Connection from '../transport/Connection.mjs'; class Peer extends EventEmitter { @@ -29,40 +29,46 @@ class Peer extends EventEmitter { // Fetch the remote's id } + /////////////////////////////////////////////////////////////////////////// + /** * Accepts an existing connection as a new Peer. * @param {Connection} connection The Connection to accept. * @return {Promise} A Promise that resolves once the initial handshake is complete. */ - __accept(connection) { - return new Promise((resolve, reject) => { - this.connection = connection; - this.connection.on("message-request-id", (msg) => { - this.connection.id = msg.my_id; - this.connection.send("id", { my_id: this.server.our_id }) - .then(resolve, reject); - }); - }); + async __accept(connection) { + this.connection = connection; + const [ msg ] = await once(this.connection, "message-hello"); + this.__handle_hello(msg); + + this.emit("connect"); } /** * Initiates the handshake after opening a new connection. * @return {Promise} A Promise that resolves after the initial peer handshake is complete. */ - __initiate() { - return new Promise((resolve, reject) => { - this.connection.send("request-id", { my_id: this.server.our_id }) - .then(() => { - this.connection.once("message-id", (msg) => { - this.id = msg.my_id; - - this.emit("connect"); - resolve(); - }); - }, reject); + async __initiate() { + await this.__send_hello(); + const [ msg ] = await once(this.connection, "message-hello"); + this.__handle_hello(msg); + + this.emit("connect"); + } + + __handle_hello(msg) { + this.id = msg.id; + } + + async __send_hello() { + await this.connection.send("hello", { + id: this.server.our_id, + peers: this.server.peers() }); } + /////////////////////////////////////////////////////////////////////////// + async destroy() { await this.connection.destroy(); this.emit("destroy"); diff --git a/src/lib/agent/PeerServer.mjs b/src/lib/agent/PeerServer.mjs index 5a4dac7..403e4a2 100644 --- a/src/lib/agent/PeerServer.mjs +++ b/src/lib/agent/PeerServer.mjs @@ -70,7 +70,7 @@ class PeerServer extends EventEmitter { * Returns a list of all currently known peer addresses. * @return {{address:string,port:number}[]} */ - peer_addresses() { + peer() { return this.peers.map((peer) => peer.remote_endpoint) .filter(el => typeof el.addr === "string" && typeof el.port === "number"); }