-
Notifications
You must be signed in to change notification settings - Fork 18
/
chat.js
46 lines (31 loc) · 920 Bytes
/
chat.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
37
38
39
40
41
42
43
44
45
46
var DEBUG = true
var PORT = 3000
var INIT_MESSAGES = 5
var http = require('http')
var server = http.createServer()
server.listen(PORT)
var io = require('socket.io').listen(server)
io.set ('transports', ['xhr-polling', 'jsonp-polling'])
var messages = new Array()
Array.prototype.inject = function(element) {
if (this.length >= INIT_MESSAGES) {
this.shift()
}
this.push(element)
}
io.sockets.on('connection', function(client) {
if (DEBUG)
console.log("New Connection: ", client.id)
client.emit("init", JSON.stringify(messages))
client.on('msg', function(msg) {
if (DEBUG)
console.log("Message: " + msg)
var message = JSON.parse(msg)
messages.inject(message)
client.broadcast.emit('msg', msg)
})
client.on('disconnect', function() {
if (DEBUG)
console.log("Disconnected: ", client.id)
})
})