-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
66 lines (57 loc) · 1.95 KB
/
server.js
File metadata and controls
66 lines (57 loc) · 1.95 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
'use strict';
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const staticFile = require('connect-static-file');
var users = [];
app.use('/index.js', staticFile(__dirname + '/assets/js/index.js'));
app.use('/index.css', staticFile(__dirname + '/assets/css/index.css'));
app.get('/', function(req, res) {
res.sendfile('assets/html/chat.html');
});
io.on('connection', function(socket) {
socket.join('chat');
socket.on('setUsername', function(data) {
var user = {
id : socket.id,
name: data
};
if (users.indexOf(user.name) > -1 && user.name !== 'Anonymous') {
socket.emit('userExists', 'Username: ' + user.name + ' already exists.');
} else {
users.push(user);
socket.emit('userSet', {id: user.id, username: user.name});
io.sockets.emit('updateUserList', users);
io.sockets.emit('alertNewUser', user.name);
}
});
socket.on('msg', function(data) {
io.sockets.emit('newmsg', data);
});
socket.on('updateName', function(data) {
users.map(function(obj, index) {
if (obj.name === data.old) {
obj.name = data.new;
}
}).filter(isFinite)[0];
io.sockets.emit('updateUserList', users);
});
socket.on('exit', function(data) {
socket.emit('updateUserList', users);
console.log("backend exit");
io.sockets.emit('alertUserLeft', data.name);
var i = users.map(function(obj, index) {
if (obj.id === data.id) {
return index;
}
}).filter(isFinite)[0];
users.splice(i, 1);
setTimeout( function() {
io.sockets.emit('updateUserList', users);
socket.disconnect();
}, 500);
});
});
http.listen(process.env.PORT || 3000, function() {
console.log('listening on localhost:3000');
});