-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPeer Comm
68 lines (59 loc) · 1.72 KB
/
Peer Comm
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
57
58
59
60
61
62
63
64
65
66
67
68
// const wrtc = require('wrtc');
// const Exchange = require('peer-exchange');
// const p2p = new Exchange(...);
// const net = require("net");
// const messageType = { ... };
// const { ... } = messageType;
// class PeerToPeer {
// constructor(karchain) { ... }
// startServer(port) { ... }
// discoverPeers() { ... }
// connectToPeer(host, port) { ... }
// closeConnection() { ... }
broadcastLatest() {
this.broadcast(Messages.sendLatestBar(this.karchain.latestBar));
}
broadcast(message) {
this.peers.forEach(peer => this.write(peer, message));
}
write(peer, message) {
peer.write(JSON.stringify(message));
}
initConnection(connection) {
this.peers.push(connection);
this.initMessageHandler(connection);
this.initErrorHandler(connection);
this.write(connection, Messages.getLatestBar());
}
initMessageHandler(connection) {
connection.on("data", data => {
const message = JSON.parse(data.toString("utf8"));
this.handleMessage(connection, message);
});
}
initErrorHandler(connection) {
connection.on("error", err => {
throw err;
});
}
handleMessage(peer, message) {
switch (message.type) {
case REQUEST_LATEST_BAR:
this.write(peer, Messages.sendLatestBar(this.karchain.latestBar));
break;
case REQUEST_KARCHAIN:
this.write(peer, Messages.sendKarchain(this.karchain.get()));
break;
case RECEIVE_LATEST_BAR:
this.handleReceivedLatestBar(message, peer);
break;
case RECEIVE_KARCHAIN:
this.handleReceivedKarchain(message);
break;
default:
throw "Received invalid message.";
}
}
// }
// module.exports = PeerToPeer;
// class Messages { ... }