forked from geekuillaume/Node.js-Chat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
98 lines (84 loc) · 2.47 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
// Customization
var appPort = 16558;
// Librairies
var express = require('express'), app = express();
var http = require('http')
, server = http.createServer(app)
, io = require('socket.io').listen(server);
var jade = require('jade');
// var io = require('socket.io').listen(app);
var pseudoArray = ['admin']; //block the admin username (you can disable it)
// Views Options
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set("view options", { layout: false })
app.configure(function() {
app.use(express.static(__dirname + '/public'));
});
// Render and send the main page
app.get('/', function(req, res){
res.render('home.jade');
});
server.listen(appPort);
// app.listen(appPort);
console.log("Server listening on port 16558");
// Handle the socket.io connections
var users = 0; //count the users
io.sockets.on('connection', function (socket) { // First connection
users += 1; // Add 1 to the count
reloadUsers(); // Send the count to all the users
socket.on('message', function (data) { // Broadcast the message to all
if(pseudoSet(socket))
{
var transmit = {date : new Date().toISOString(), pseudo : returnPseudo(socket), message : data};
socket.broadcast.emit('message', transmit);
console.log("user "+ transmit['pseudo'] +" said \""+data+"\"");
}
});
socket.on('setPseudo', function (data) { // Assign a name to the user
if (pseudoArray.indexOf(data) == -1) // Test if the name is already taken
{
socket.set('pseudo', data, function(){
pseudoArray.push(data);
socket.emit('pseudoStatus', 'ok');
console.log("user " + data + " connected");
});
}
else
{
socket.emit('pseudoStatus', 'error') // Send the error
}
});
socket.on('disconnect', function () { // Disconnection of the client
users -= 1;
reloadUsers();
if (pseudoSet(socket))
{
var pseudo;
socket.get('pseudo', function(err, name) {
pseudo = name;
});
var index = pseudoArray.indexOf(pseudo);
pseudo.slice(index - 1, 1);
}
});
});
function reloadUsers() { // Send the count of the users to all
io.sockets.emit('nbUsers', {"nb": users});
}
function pseudoSet(socket) { // Test if the user has a name
var test;
socket.get('pseudo', function(err, name) {
if (name == null ) test = false;
else test = true;
});
return test;
}
function returnPseudo(socket) { // Return the name of the user
var pseudo;
socket.get('pseudo', function(err, name) {
if (name == null ) pseudo = false;
else pseudo = name;
});
return pseudo;
}