-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathwebsocket.js
48 lines (35 loc) · 1.31 KB
/
websocket.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
const ws = require('ws');
const { Logger, LogLevel } = require('./utils/logger');
const log = new Logger(LogLevel.DEBUG)
class WebSocket extends ws.Server {
constructor() {
super({ port: 8080 });
this.connectedClient = null; // Store the connected client WebSocket instance
this.on('connection', this.handleConnection);
}
handleConnection(ws) {
log.success('WS : A new client connected.');
// Store the connected client WebSocket instance
this.connectedClient = ws;
ws.on('message', (message) => {
log.info('Received message from client:', message);
// Send a response back to the client
ws.send('Received: ' + message);
// Send a message to the connected client
this.sendMessageToClient('Hello from the server!');
});
ws.on('close', () => {
log.info('WS : Client disconnected.');
// Clear the connected client reference when the client disconnects
this.connectedClient = null;
});
}
sendMsg(message) {
if (this.connectedClient) {
if (typeof (message) == 'object')
message = JSON.stringify(message)
this.connectedClient.send(message);
}
}
}
exports.WebSocket = WebSocket