-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
87 lines (75 loc) · 2.14 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
var express = require('express');
var moment = require('moment');
var port = process.env.PORT || 3000,
app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(express.static(__dirname + '/public'));
//memory cache
var clientInfo = {};
// Sends current users to provided socket
function sendCurrentUsers (socket) {
var info = clientInfo[socket.id];
var users = [];
if(typeof info === 'undefined') {
return;
}
Object.keys(clientInfo).forEach(function (socketId){
var userInfo = clientInfo[socketId];
if(info.room === userInfo.room) {
users.push(userInfo.name);
}
});
socket.emit('message', {
name: 'System',
text: 'Current users in chatroom: ' + users.join(', '),
timestamp: moment().valueOf()
})
}
//event on 'connection'
io.on('connection', function(socket){
console.log('user connected')
//event on 'disconnect' leave room msg emit
socket.on('disconnect', function (){
var userData = clientInfo[socket.id];
if(typeof userData !== 'undefined'){
socket.leave(userData.room);
io.to(userData.room).emit('message', {
name: 'System',
text: userData.name + ' has left',
timestamp: moment().valueOf()
});
delete clientInfo[socket.id];
}
});
//broadcast is for everyone
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()
})
});
//io.to is specific to everyone that is in room
socket.on('message', function (message){
console.log('Message received: ' + message.text);
if(message.text === '@currentUsers') {
sendCurrentUsers(socket);
} else {
//send to everyone excluding sender: socket.broadcast.emit('message', message);
message.timestamp = moment().valueOf();
io.to(clientInfo[socket.id].room).emit('message', message);
}
});
//socket.emit is for everyone within chat
socket.emit('message', {
name: 'System login on',
text: 'Welcome to chat application!',
timestamp: moment().valueOf()
})
});
http.listen(port, function(){
console.log('server listening on: ' + port)
});