-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathTCP.ts
56 lines (41 loc) · 1.34 KB
/
TCP.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import msg from 'axon';
import {Mokka} from '../consensus/main';
class TCPMokka extends Mokka {
private sockets: Map<string, any> = new Map<string, any>();
public initialize() {
this.logger.info(`initializing reply socket on port ${this.address}`);
this.sockets.set(this.address, msg.socket('sub-emitter'));
this.sockets.get(this.address).bind(this.address);
this.sockets.get(this.address).on('message', (data: Buffer) => {
this.emitPacket(data);
});
this.sockets.get(this.address).on('error', () => {
this.logger.error(`failed to initialize on port: ${this.address}`);
});
}
/**
* The message to write.
*
* @param {string} address The peer address
* @param {Object} packet The packet to write to the connection.
* @api private
*/
public async write(address: string, packet: Buffer): Promise<void> {
if (!this.sockets.has(address)) {
this.sockets.set(address, msg.socket('pub-emitter'));
this.sockets.get(address).connect(address);
}
this.sockets.get(address).emit('message', packet);
}
public async disconnect(): Promise<void> {
await super.disconnect();
for (const socket of this.sockets.values()) {
socket.close();
}
}
public async connect(): Promise<void> {
this.initialize();
await super.connect();
}
}
export default TCPMokka;