-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.js
46 lines (34 loc) · 1.1 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
var express = require('express');
var path = require('path');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var _ = require('lodash');
var port = process.env.PORT || 3000;
app.use(express.static(path.join(__dirname, 'public')));
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
var users = [];
io.on('connection', function(socket) {
socket.on('online user', function(user) {
user.socket_id = socket.id;
var foundUser = _.find(users, {id: user.id});
if (foundUser) {
foundUser.socket_id = socket.id;
} else {
users.push(user);
}
io.emit('online users list', users);
});
socket.on('chat message', function(msg, toUserID, from) {
var toUser = _.find(users, {id: toUserID});
socket.to(toUser.socket_id).emit('chat message', msg, from);
});
socket.on('disconnect', function() {
users = _.reject(users, {socket_id: socket.id});
});
});
http.listen(port, function(){
console.log('listening on *:' + port);
});