forked from phil-giambra/code_bits
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwebsocket_basic_server.js
More file actions
76 lines (53 loc) · 1.72 KB
/
websocket_basic_server.js
File metadata and controls
76 lines (53 loc) · 1.72 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
const WebSocket = require('ws');
let wss_port = 5555
let client_id = 0
let CLIENTS = { }
let wss_m = null
function startWebSocketServer() {
wss_m = new WebSocket.Server({ port: wss_port });
wss_m.on('connection', function connection(ws, req) {
console.log("INFO--> New Connection ");
// give an id and setup client in CLIENTS
ws.client_id = client_id;
client_id += 1;
CLIENTS[ws.client_id] = { ws_ref: ws , id : ws.client_id }
// handle incoming messages
ws.on('message', function incoming(message) {
let packet = JSON.parse( message )
packet.client_id = ws.client_id
console.log("INFO--> New Message from Client");
});
// handle disconnects
ws.on('close', function close() {
let id = ws.client_id
delete CLIENTS[id];
console.log(`INFO--> Client disconnected: id ${ id } `);
});
ws.on('error', function error(err) {
console.log("websocket error", err);
});
});
}
function stopWebSocketServer() {
if (wss_m !== null) {// maybe add socket status check
for (let clientid in CLIENTS) {
CLIENTS[clientid].ws_ref.close()
}
}
wss_m.close();
wss_m = null
}
function sendToOneClient(packet, clientid) {
if (wss_m !== null) {// maybe add socket status check
if (CLIENTS[clientid]) {
CLIENTS[clientid].ws_ref.send(JSON.stringify(packet))
}
}
}
function sendToAllClients(packet) {
if (wss_m !== null) {// maybe add socket status check
for (let client_id in CLIENTS) {
CLIENTS[client_id].ws_ref.send(JSON.stringify(packet))
}
}
}