-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
38 lines (30 loc) · 912 Bytes
/
index.js
File metadata and controls
38 lines (30 loc) · 912 Bytes
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
var WebSocketServer = require("ws").Server
var http = require("http")
var express = require("express")
var app = express()
var port = process.env.PORT || 5000
var counter = 0
app.use(express.static(__dirname + "/"))
var server = http.createServer(app)
server.listen(port)
console.log("http server listening on %d", port)
var wss = new WebSocketServer({server: server})
console.log("websocket server created")
wss.broadcast = function(data) {
for (var i in this.clients)
this.clients[i].send(data);
};
wss.on("connection", function(ws) {
console.log("websocket connection open")
counter++
console.log(counter)
wss.broadcast( JSON.stringify({counter: counter}) )
ws.on('message', function(data, flags) {
wss.broadcast(data);
})
ws.on("close", function() {
console.log("websocket connection closed")
counter --
wss.broadcast( JSON.stringify({counter: counter}) )
})
})