-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
45 lines (38 loc) · 1.05 KB
/
app.js
File metadata and controls
45 lines (38 loc) · 1.05 KB
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
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
usernames = []; // Array of Connected Users
server.listen(process.env.PORT || 3000);
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
// Server side
io.sockets.on('connection', function(socket) {
socket.on('new user', function(data, callback) {
if (usernames.indexOf(data) != -1) {
callback(false);
} else {
callback(true);
socket.username = data;
usernames.push(socket.username);
updateUsernames();
}
});
// Update usernames
function updateUsernames() {
io.sockets.emit('usernames', usernames);
};
// Send message
socket.on('send message', function(data) {
io.sockets.emit('new message', { msg: data, user: socket.username });
});
// Disconnect and delete the username from the chat
socket.on('disconnect', function(data) {
if ( !socket.username) {
return;
}
usernames.splice(usernames.indexOf(socket.username), 1);
updateUsernames();
});
});