-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
87 lines (70 loc) · 2.22 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 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 = {};
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: 'Cüik spy',
text: 'Current users: ' + users.join(', '),
timestamp: moment().valueOf(),
master: "info"
});
}
io.on('connection', function (socket) {
socket.on('disconnect', function () {
var userData = clientInfo[socket.id];
if (typeof userData !== 'undefined') {
socket.leave(userData.room);
io.to(userData.room).emit('message', {
name: 'Cüik spy',
text: userData.name + ' has left :(',
timeStamp: moment().valueOf(),
master: "danger"
});
delete clientInfo[socket.id];
}
});
socket.emit('message', {
name: 'Cüik spy',
text: 'Start typing and hit enter to send a <i>Cüik</i> message!',
timeStamp: moment().format('x').valueOf(),
master: "info"
});
socket.on('joinRoom', function (req) {
clientInfo[socket.id] = req;
socket.join(req.room);
socket.broadcast.to(req.room).emit('message', {
name: 'Cüik spy',
text: req.name + ' has joined!',
timeStamp: moment().valueOf(),
master: "success"
})
});
socket.on('message', function (message) {
if (message.text === '@currentUsers') {
sendCurrentUsers(socket);
}
else {
message.timeStamp = moment().format('x');
io.to(clientInfo[socket.id].room).emit('message', message);
}
});
});
http.listen(PORT, function () {
console.log('Server started on port ' + PORT);
});