-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
47 lines (37 loc) · 1.14 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
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
users = [];
connections = [];
var rooms = ['room1', 'room2', 'room3'];
server.listen(process.env.PORT || 3000);
console.log('Server running...');
app.get('/', function(req, res){
res.sendFile(__dirname + '/templates/index.html');
});
io.sockets.on('connection', function(socket){
connections.push(socket);
console.log('Connected: %s sockets connected', connections.length);
//Disconnect
socket.on('disconnect', function(data){
users.splice(users.indexOf(socket.username), 1);
updateUsernames();
connections.splice(connections.indexOf(socket), 1);
console.log('Disconnected: %s sockets connected', connections.length);
});
//Send Message
socket.on('send message', function(data){
io.sockets.emit('new message', {msg: data, user: socket.username});
});
//New User
socket.on('new user', function(data, callback){
callback(true);
socket.username = data;
users.push(socket.username);
updateUsernames();
});
function updateUsernames(){
io.sockets.emit('get users', users);
};
});