-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
91 lines (73 loc) · 2.16 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
var PORT = process.env.PORT || 3000;
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var moment = require('moment');
app.use(express.static(__dirname + '/public'));
var clientInfo = {};
//sends current users to defined socket
function sendCurrentUsers(socket) {
var info = clientInfo[socket.id];
var users = [];
console.log('info may be undefined');
if(typeof info === 'undefined') {
return;
}
console.log(info);
Object.keys(clientInfo).forEach(function(socketId) {
var userInfo = clientInfo[socketId];
if (info.room === userInfo.room) {
users.push(userInfo.name);
}
});
console.log(users);
socket.emit('message', {
name: 'System',
text: 'Current users: ' + users.join(', '),
timestamp: moment().valueOf()
});
};
io.on('connection', function(socket){
console.log('User connected via socket.io');
socket.on('disconnect', function() {
var userData = clientInfo[socket.id];
if(typeof userData !== 'undefined') {
socket.leave(clientInfo[socket.id].room);
io.to(userData.room).emit('message', {
name: 'System',
text: userData.name + ' has left the room.',
timestamp: moment().valueOf()
});
delete clientInfo[socket.id];
}
});
socket.on('joinRoom', function(req) {
clientInfo[socket.id] = req;
socket.join(req.room);
socket.broadcast.to(req.room).emit('message', {
name: 'System',
text: req.name + ' has joined.',
timestamp: moment().valueOf()
});
});
socket.on('message', function(message){
console.log('Message recieved ' + message.text);
if(message.text === '@currentUsers') {
console.log('current users');
sendCurrentUsers(socket);
} else {
message.timestamp = moment().valueOf();
io.to(clientInfo[socket.id].room).emit('message', message);
}
});
//timestamp property - Javascript timestamp (miliseconds)
socket.emit('message', {
name: 'System',
text: 'Welcome to the chat application',
timestamp: moment().valueOf()
});
});
http.listen(PORT, function(){
console.log('Server started.');
});