-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
40 lines (37 loc) · 1.08 KB
/
server.js
File metadata and controls
40 lines (37 loc) · 1.08 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
var ws = require("nodejs-websocket")
var PORT = 3000
var clientCount = 0
// Scream server example: "hi" -> "HI!!!"
var server = ws.createServer(function(conn){
console.log("New connection")
clientCount++
conn.nickname = 'user' + clientCount
var mes = {}
mes.type = "entering"
mes.data = conn.nickname + 'comes in'
broadcast(JSON.stringify(mes))
conn.on("text",function(str){
console.log("Received " + str)
var mes = {}
mes.type = "message"
mes.data = conn.nickname + " says: " + str
broadcast(JSON.stringify(mes))
})
conn.on("error",function(err){
console.log("handle err")
console.log(err)
})
conn.on("close",function(code,reason){
console.log("Connection closed")
var mes = {}
mes.type = "leaving"
mes.data = conn.nickname + ' leave'
broadcast(JSON.stringify(mes))
})
}).listen(PORT)
console.log("websocket server listening on " + PORT)
function broadcast(str){
server.connections.forEach(function(connection){
connection.sendText(str)
})
}