-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
executable file
·36 lines (31 loc) · 1.07 KB
/
server.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
// Importing the required modules
const WebSocketServer = require('ws');
// Creating a new websocket server
const wss = new WebSocketServer.Server({ port: 8080, maxPayload: 100000000})
var clients = {};
var ctr = 0;
// Creating connection using websocket
wss.on("connection", ws => {
console.log("new client connected");
clients[ctr++] = ws;
// sending message
ws.on("message", data => {
jsonData = JSON.parse(data);
clients[jsonData.sender] = ws;
console.log(`Client ${jsonData.sender} => ${JSON.stringify(jsonData)}`);
//console.log(`Client has sent us: ${JSON.stringify(data)}`)
if(jsonData.recipient && clients[jsonData.recipient])
{
clients[jsonData.recipient].send(data);
}
});
// handling what to do when clients disconnects from server
ws.on("close", () => {
console.log("the client has connected");
});
// handling client connection error
ws.onerror = function () {
console.log("Some Error occurred")
}
});
console.log("The WebSocket server is running on port 8080");