-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.js
More file actions
108 lines (96 loc) · 2.83 KB
/
client.js
File metadata and controls
108 lines (96 loc) · 2.83 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
const Socket = require("./socket");
const ClientServerBase = require("./clientServerBase");
const decipher = require("./encryption").decrypt;
// ===========================
// Client Class
class Client extends ClientServerBase {
/**
* Setup udp socket connection to server
* @param {Object} param0 - port, address, clientID, encryptionKey
*/
constructor({
port,
address,
clientID,
encryptionKey,
connectionTimeout,
retryTimeout,
}) {
super({ connectionTimeout, retryTimeout });
this.socket = undefined;
this.port = port || 41234;
this.address = address || "localhost";
this.clientID = clientID;
this.encryptionKey = encryptionKey;
this.connectionTimeout = connectionTimeout || 1000; // 1 seconds
this.connectionInterval = undefined;
this.socket = new Socket({
port,
address,
serverSocket: this.server,
isClient: true,
clientID,
encryptionKey,
retryTimeout: this.retryTimeout,
connectionTimeout: this.connectionTimeout,
parentDisconnect: this.disconnect.bind(this),
});
this.setupConnection();
// this.connectionWatchDog();
this.connectionRetry();
}
/**
* return a socket
*/
getSocket() {
return this.socket;
}
setupConnection() {
// setup connection
this.socket.emit(null, null, {
type: "connect",
socketID: this.socket.socketID,
});
this.socket.deleted = false;
}
connected({ data }) {
// start keepAlive
this.socket._keepalive();
// set socketID
this.socket.socketID = data.socketID;
// emit data event
this.socket.emitLocal("connected", data.message);
}
disconnect() {
this.socket.connected = false;
}
/**
* Try to reconnect as long as socket is disconnected
*/
connectionRetry() {
this.connectionInterval = setInterval(() => {
// try to setupConnection as log as socket is disconnected
if (!this.socket.connected) this.setupConnection();
}, this.connectionTimeout);
}
/**
* Client Decryption handling
* @param {*} data
* @param {*} iv
* @param {*} clientID
*/
async decrypt(data, iv, clientID) {
// ignore message if encryption key is not provided
if (clientID && iv && !this.encryptionKey) return;
return await decipher(data, iv, this.encryptionKey);
}
/**
* destroys all intervals and disconnects socket
*/
destroy() {
clearInterval(this.connectionInterval);
this.socket.disconnect();
this.socket.removeAllListeners();
}
}
module.exports = Client;