-
Notifications
You must be signed in to change notification settings - Fork 9
/
app.js
46 lines (40 loc) · 1.35 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
var express = require('express');
var app = module.exports = express.createServer();
var io = require('socket.io').listen(app);
//configure express
app.configure(function(){
app.use(express.static(__dirname + '/public'));
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
//start the http server
app.listen(process.env.C9_PORT);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
//setup the chat server
var clients = [];
io.sockets.on('connection', function (socket) {
//add the new client and send welcome message
clients.push(socket);
socket.emit('message', { time: new Date().toLocaleTimeString(), person: 'Chat Server', message: 'Welcome to Chat!' });
//relay messages
socket.on('message', function (data) {
//add server time to the message
data.time = new Date().toLocaleTimeString();
//log the message
console.log(data.person + ': ' + data.message);
//send messages to all clients
for (var i = 0; i < clients.length; i++)
{
clients[i].emit('message', data);
}
});
//notify pending messages
socket.on('typing', function (data) {
//log the message
console.log(data.person + ': is typing');
//send messages to all clients
for (var i = 0; i < clients.length; i++)
{
clients[i].emit('typing', data);
}
});
});