-
Notifications
You must be signed in to change notification settings - Fork 0
/
NetworkNode.js
88 lines (73 loc) · 1.9 KB
/
NetworkNode.js
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
var Packet = require('./Packet');
var CONNECTION_SPEED = 50;
class NetworkNode {
/**
*
* @param {HTMLObjectElement} htmlNode
*/
constructor(htmlNode = null, lifetime = 2*CONNECTION_SPEED) {
this.interfaces = {
0: null,
1: null
};
this.data = null;
this.htmlNode = htmlNode;
this.lifetime = lifetime;
this.timer = null;
this.sendTimer = [null, null];
}
updateHTML() {
if(this.htmlNode != null) {
this.htmlNode.innerHTML = this.data;
}
}
/**
*
* @param {*} data
* @param {NetworkNode} input
*/
receive(packet, input) {
if(this.data != null) {
packet.from = null;
packet.to = null;
packet.data = "###";
}
this.data = packet;
this.updateHTML();
if(this.interfaces[0] === input) {
this.send(1, packet);
} else if(this.interfaces[1] === input) {
this.send(0, packet);
} else {
console.error(input);
throw new Error("Received packet from not directly connected node");
}
if(this.timer !== null) {
clearTimeout(this.timer);
}
this.timer = setTimeout(() => {
this.data = null;
this.timer = null;
this.updateHTML();
}, this.lifetime);
}
/**
* @param {*} data
* @param {*} recipient
*/
send(recipient, packet) {
clearTimeout(this.sendTimer[recipient]);
this.sendTimer[recipient] = setTimeout(() => {
this.interfaces[recipient].receive(packet, this);
}, CONNECTION_SPEED)
}
/**
*
* @param {NetworkNode} Cable
* @param {String} id
*/
join(node, id = 0) {
this.interfaces[id] = node;
}
}
module.exports = NetworkNode;