71 lines
1.4 KiB
JavaScript
71 lines
1.4 KiB
JavaScript
|
"use strict";
|
||
|
|
||
|
import net from 'net';
|
||
|
import { EventEmitter, once } from 'events';
|
||
|
|
||
|
import l from 'log';
|
||
|
import nexline from 'nexline';
|
||
|
|
||
|
import settings from '../../settings.mjs';
|
||
|
|
||
|
/**
|
||
|
* Represents a connection to a single endpoint.
|
||
|
*/
|
||
|
class Connection extends EventEmitter {
|
||
|
constructor() {
|
||
|
super();
|
||
|
}
|
||
|
|
||
|
/**
|
||
|
* Connects to a peer and initialises a secure TCP connection thereto.
|
||
|
* @param {string} address The address to connect to.
|
||
|
* @param {string} port The TCP port to connect to.
|
||
|
* @return {net.Socket} A socket setup for secure communication.
|
||
|
*/
|
||
|
async connect(address, port) {
|
||
|
this.address = address; this.port = port;
|
||
|
this.socket = new new.Socket();
|
||
|
this.socket.connect({
|
||
|
address, port
|
||
|
});
|
||
|
await once(this.socket, "connect");
|
||
|
this.socket.setKeepAlive(true);
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
|
||
|
// this.reader = nexline({
|
||
|
// input: this.socket
|
||
|
// });
|
||
|
//
|
||
|
// this.read_task = read_loop();
|
||
|
}
|
||
|
|
||
|
destroy() {
|
||
|
this.socket.destroy();
|
||
|
this.emit("destroy");
|
||
|
}
|
||
|
|
||
|
async read_loop() {
|
||
|
try {
|
||
|
for await (let line of this.reader) {
|
||
|
handle_message(line);
|
||
|
}
|
||
|
}
|
||
|
catch(error) {
|
||
|
l.warn(`Warning: Killing connection to ${this.address}:${this.port} after error: ${settings.cli.verbose ? error : error.message}`);
|
||
|
}
|
||
|
finally {
|
||
|
this.destroy();
|
||
|
}
|
||
|
}
|
||
|
|
||
|
handle_message(text) {
|
||
|
let message = JSON.parse(text);
|
||
|
|
||
|
}
|
||
|
}
|
||
|
|
||
|
export default Connection;
|