-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex-ws.js
More file actions
51 lines (40 loc) · 1.13 KB
/
index-ws.js
File metadata and controls
51 lines (40 loc) · 1.13 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
const express = require("express");
const server = require("http").createServer();
const app = express();
app.get("/", function (req, res) {
res.sendFile("index.html", { root: __dirname });
});
server.on("request", app);
server.listen(3000, function () {
console.log("server listen to port 3000");
});
/** Begin websocket*/
const WebSocketServer = require("ws").Server;
const wss = new WebSocketServer({ server: server });
wss.on("connection", function connection(ws) {
const numClients = wss.clients.size;
console.log("clients connected: ", numClients);
wss.broadcast(`Current visitors: ${numClients}`);
if (ws.readyState === ws.OPEN) {
ws.send("welcome!");
}
ws.on("close", function close() {
wss.broadcast(`Current visitors: ${wss.clients.size}`);
console.log("A client has disconnected");
});
ws.on("error", function error() {
//
});
});
/**
* Broadcast data to all connected clients
* @param {Object} data
* @void
*/
wss.broadcast = function broadcast(data) {
console.log("Broadcasting: ", data);
wss.clients.forEach(function each(client) {
client.send(data);
});
};
/** End Websocket *****/