-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsocket.js
More file actions
195 lines (178 loc) · 5.92 KB
/
socket.js
File metadata and controls
195 lines (178 loc) · 5.92 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
const { v4: uuidv4 } = require("uuid");
const { waitingAck } = require("./data");
const { encrypt } = require("./encryption");
const Events = require("events").EventEmitter;
const messageFragmentation = require("./messageFragmentation");
/**
* Used to give a unique id to each ack message
*/
let ackCounter = 0;
// ===========================
// Socket Class
/**
* dgram udp socket used for server to server communication
*/
class Socket extends Events {
/**
*
* @param {Object} options - serverPort, serverAddress
*/
constructor({
port,
address,
serverSocket,
isClient = false,
clientID = undefined,
encryptionKey = undefined,
retryTimeout,
connectionTimeout,
parentDisconnect,
}) {
super();
this.socketID = !isClient ? uuidv4() : "";
this.isClient = isClient;
this.socket = serverSocket;
this.port = port;
this.address = address;
this.deleted = false;
this.keepAliveTime = new Date();
this.keepAlive = undefined;
this.connected = false;
this.clientID = clientID; // used to identify client
this.encryptionKey = encryptionKey; // used to encrypt/decrypt messages
this.retryTimeout = retryTimeout || 500;
this.connectionTimeout = connectionTimeout || 1000; // 1 seconds
this.frag = new messageFragmentation(this.socket);
this.parentDisconnect = parentDisconnect;
this.on("connected", () => {
this.connected = true;
});
this.on("disconnected", () => {
this.connected = false;
});
this._keepalive();
}
// start client keepAlive
_keepalive() {
if (this.keepAlive) return;
this.keepAlive = setInterval(() => {
this.connectionWatchDog();
}, this.connectionTimeout / 4);
}
/**
* emit a message to a socket
* @param {String} topic
* @param {Any} message
* @param {Object} options - type (data (default), keepAlive, ack), guaranteeDelivery (used for guaranteed delivery)
*/
emit(topic, message, options = {}) {
this._emit(
this.socket,
this.port,
this.address,
topic,
message,
options
);
}
/**
* emit a message to a socket
* @param {Object} _dgram - udp socket
* @param {Number} port - destination port
* @param {String} address - destination address
* @param {String} topic - topic
* @param {Any} message - message
* @param {Object} options - type (data (default), keepAlive, ack), guaranteeDelivery (used for guaranteed delivery), ackID (used for guaranteed delivery), socketID
*/
async _emit(_dgram, port, address, topic, message, options) {
// wait socket to get a socketID
while (!this.socketID && options.type != "connect") {
await new Promise((resolve) => setTimeout(resolve, 100));
}
// create guaranteeDelivery
if (!options.ackID && options.guaranteeDelivery) {
ackCounter++;
options.ackID = ackCounter;
}
let data = {
topic: topic,
message: message,
ackID: options.ackID,
socketID: this.socketID,
};
// encrypt data if encryptionKey is provided
if (
this.clientID &&
this.encryptionKey &&
(!options.type ||
options.type == "data" ||
options.type == "connect")
) {
data = await encrypt(JSON.stringify(data), this.encryptionKey);
}
const M = JSON.stringify({
type: options.type || "data",
data: data.encryptedData || data,
iv: data.iv,
clientID: this.clientID,
});
this.frag.sendFragmentedMessage(M, port, address);
// if guaranteeDelivery is true, add message to waitingAck
options.guaranteeDelivery &&
this.waitForAck(_dgram, port, address, topic, message, options);
}
/**
* Wait for ack from socket
* @param {Object} _dgram - udp socket
* @param {Number} port - destination port
* @param {String} address - destination address
* @param {String} topic - topic
* @param {Any} message - message
* @param {Object} options - type (data (default), keepAlive, ack), guaranteeDelivery (used for guaranteed delivery), ackID (used for guaranteed delivery), socketID
*/
waitForAck(_dgram, port, address, topic, message, options) {
waitingAck[options.ackID] = { ackID: options.ackID };
// wait for 2 seconds for ack
setTimeout(() => {
if (waitingAck[options.ackID] && !this.deleted) {
// re-emit message
this._emit(_dgram, port, address, topic, message, {
...options,
socketID: this.socketID,
});
}
}, this.retryTimeout);
}
/**
* Disconnect socket
*/
disconnect() {
clearInterval(this.keepAlive);
this.keepAlive = undefined;
this.parentDisconnect(this.socketID);
this.emitLocal("disconnected", this.socketID);
if (!this.isClient) this.removeAllListeners(); // only remove listener if client
console.log("disconnecting socket: " + this.socketID);
this.deleted = true;
this.connected = false;
}
/**
* Connection WatchDog
*/
connectionWatchDog() {
this.emit(null, null, { type: "keepAlive" });
// check if connection is alive
if (new Date() - this.keepAliveTime > this.connectionTimeout) {
this.disconnect();
}
}
/**
* Emit an event with eventemitter
* @param {string} eventName
* @param {Any} data
*/
emitLocal(eventName, data) {
super.emit(eventName, data);
}
}
module.exports = Socket;