-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
91 lines (70 loc) · 2.42 KB
/
app.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/**
* Module dependencies.
*/
var express = require('express')
var app = module.exports = express.createServer()
, jade = require('jade')
, json2 = require('JSON')
, io = require('socket.io').listen(app)
, _ = require('underscore')._
, Backbone = require('backbone')
, redis = require('redis')
, rc = redis.createClient()
, models = require('./models/models');
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set('view options', {layout: false});
});
app.get('/*.(js|css)', function(req, res){
res.sendfile('./'+req.url);
});
app.get('/', function(req, res){
res.render('index');
});
var activeClients = 0;
var nodeChatModel = new models.NodeChatModel();
rc.lrange('chatentries', -10, -1, function(err, data) {
if (data) {
_.each(data, function(jsonChat) {
var chat = new models.ChatEntry();
chat.mport(jsonChat);
nodeChatModel.chats.add(chat);
});
console.log('Revived ' + nodeChatModel.chats.length + ' chats');
}
else {
console.log('No data returned for key');
}
});
io.sockets.on('connection', function(client){
activeClients += 1;
console.log('activeClients: '+ activeClients)
client.on('disconnect', function(){clientDisconnect(client)});
client.on('message', function(msg){chatMessage(client, io, msg)});
client.emit('initial', nodeChatModel.xport())
client.emit('update', {clients: activeClients})
client.broadcast.emit('update', {clients: activeClients})
});
function chatMessage(client, io, msg){
var chat = new models.ChatEntry();
chat.mport(msg);
console.log('message received: ' + msg)
rc.incr('next.chatentry.id', function(err, newId) {
chat.set({id: newId});
nodeChatModel.chats.add(chat);
console.log('(' + client.sessionId + ') ' + chat.get('id') + ' ' + chat.get('name') + ': ' + chat.get('text'));
rc.rpush('chatentries', chat.xport(), redis.print);
rc.bgsave();
client.emit('chat', chat.xport());
client.broadcast.emit('chat', chat.xport());
});
}
function clientDisconnect(client) {
activeClients -= 1;
console.log('activeClients: '+ activeClients)
client.broadcast.emit('update', {clients:activeClients})
}
app.listen(3000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);