-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
43 lines (36 loc) · 1.11 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
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
users = [];
connections = [];
server.listen(process.env.PORT || 3000);
console.log('Server running...');
app.get('/',function(req,res){
res.sendFile(__dirname + '/');
});
io.sockets.on('connection', function(socket){
connections.push(socket);
console.log('Connected: %s socket 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 socket 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);
}
});