-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
60 lines (47 loc) · 1.56 KB
/
index.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
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
var _ = require('lodash-node');
var users = [];
app.get('/', function (req, res){
res.sendfile('index.html');
});
io.on('connection', function (socket) {
socket.on('login', function (name) {
// if this socket is already connected,
// send a failed login message
if (_.findIndex(users, { socket: socket.id }) !== -1) {
socket.emit('login_error', 'You are already connected.');
}
// if this name is already registered,
// send a failed login message
if (_.findIndex(users, { name: name }) !== -1) {
socket.emit('login_error', 'This name already exists.');
return;
}
users.push({
name: name,
socket: socket.id
});
socket.emit('login_successful', _.pluck(users, 'name'));
socket.broadcast.emit('online', name);
console.log(name + ' logged in');
});
socket.on('sendMessage', function (name, message) {
var currentUser = _.find(users, { socket: socket.id });
if (!currentUser) { return; }
var contact = _.find(users, { name: name });
if (!contact) { return; }
io.to(contact.socket)
.emit('messageReceived', currentUser.name, message);
});
socket.on('disconnect', function () {
var index = _.findIndex(users, { socket: socket.id });
if (index !== -1) {
socket.broadcast.emit('offline', users[index].name);
console.log(users[index].name + ' disconnected');
users.splice(index, 1);
}
});
});
http.listen(process.env.PORT || 5000);