Peer: we can use async/await for the initial handshake
events.once(emitter, eventname) makes it so much more concise!
This commit is contained in:
parent
6f181971e3
commit
32dec3049f
2 changed files with 28 additions and 22 deletions
|
@ -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) => {
|
||||
async __accept(connection) {
|
||||
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);
|
||||
});
|
||||
});
|
||||
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;
|
||||
async __initiate() {
|
||||
await this.__send_hello();
|
||||
const [ msg ] = await once(this.connection, "message-hello");
|
||||
this.__handle_hello(msg);
|
||||
|
||||
this.emit("connect");
|
||||
resolve();
|
||||
});
|
||||
}, reject);
|
||||
}
|
||||
|
||||
__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");
|
||||
|
|
|
@ -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");
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue