-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwebSocketClient.js
More file actions
111 lines (100 loc) · 2.78 KB
/
Copy pathwebSocketClient.js
File metadata and controls
111 lines (100 loc) · 2.78 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
const Client = require('../client/client');
const WebSocket = require('ws');
/**
* WebSocket Client.
* Wraps the WebSocket that was emitted from the
* WebSocketServerListener.
* @extends {Client}
*/
class WebSocketClient extends Client {
/**
* Constructor
* @param {WebSocket} socket
* @param {Object} [options={}]
* @return {WebSocketClient}
*/
constructor(socket, {id = 0}){
super(socket, {id});
}
/**
* Get the address of the socket,
* such as 127.0.0.1, or localhost
* @return {String}
*/
getSocketAddress(){
if(this.socket){
return this.socket._socket.remoteAddress();
}
}
/**
* Get the port of the socket,
* probably between 1 to 65535
* @return {String}
*/
getSocketPort(){
if(this.socket){
return this.socket._socket.remotePort;
}
}
/**
* Attach handlers to the WebSocket.
* The websocket events will emit the standard ClientSocket events.
* If debug logs are enabled, all events are logged.
* If the socket hits max errors, the maxError event is emitted.
* @param {WebSocket} socket
*/
attachSocketHandlers(socket){
// on open, emit open and ping the socket
socket.on('open', (data) => {
this.logger.debug(`Connected:`);
this.logger.debug(data);
this.emit('open', data);
setTimeout(() => {
this.ping();
}, 1000);
})
// on message, route and emit message
socket.on('message', (data) => {
this.logger.debug('Received message:');
this.logger.debug(data);
this.routeMessage(data);
this.emit('message', data);
});
// on error, increase the max error count
// if max error is hit, emit maxError event
socket.on('error', (error) => {
this.logger.error("Socket error:");
this.logger.error(error);
this.emit('error', error);
this.error_count++;
});
// on close, emit disconnect
socket.on('close', (code, reason) => {
this.logger.debug(`Websocket closed with code: ${code}, reason: ${reason ? reason : "none"}`);
this.emit('disconnect', {code, reason});
});
}
/**
* Disconnect the client.
*/
disconnect(){
this.socket.close(0, "");
}
/**
* Write data to the socket.
* Will check if the socket is open or not.
* If it is not, fails by returning null.
* @param {*} data
* @return {*|Number|null} - returns null if it failed
*/
write(data){
if(this.socket.readyState === WebSocket.OPEN){
return this.socket.send(data);
}
else {
this.logger.error("Socket is not open");
return null;
}
}
}
module.exports = WebSocketClient;