-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
84 lines (70 loc) · 1.89 KB
/
server.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
//
// # SimpleServer
//
// A simple chat server using Socket.IO, Express, and Async.
//
var http = require('http');
var path = require('path');
var async = require('async');
var socketio = require('socket.io');
var express = require('express');
//
// ## SimpleServer `SimpleServer(obj)`
//
// Creates a new instance of SimpleServer with the following options:
// * `port` - The HTTP port to listen on. If `process.env.PORT` is set, _it overrides this value_.
//
var router = express();
var server = http.createServer(router);
var io = socketio.listen(server);
router.use(express.static(path.resolve(__dirname, 'client')));
var messages = [];
var sockets = [];
io.on('connection', function (socket) {
messages.forEach(function (data) {
socket.emit('message', data);
});
sockets.push(socket);
socket.on('disconnect', function () {
sockets.splice(sockets.indexOf(socket), 1);
updateRoster();
});
socket.on('message', function (msg) {
var text = String(msg || '');
if (!text)
return;
socket.get('name', function (err, name) {
var data = {
name: name,
text: text
};
broadcast('message', data);
messages.push(data);
});
});
socket.on('identify', function (name) {
socket.set('name', String(name || 'Anonymous'), function (err) {
updateRoster();
});
});
});
function updateRoster() {
async.map(
sockets,
function (socket, callback) {
socket.get('name', callback);
},
function (err, names) {
broadcast('roster', names);
}
);
}
function broadcast(event, data) {
sockets.forEach(function (socket) {
socket.emit(event, data);
});
}
server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function(){
var addr = server.address();
console.log("Chat server listening at", addr.address + ":" + addr.port);
});