This repository has been archived by the owner on Nov 26, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
server.js
88 lines (67 loc) · 2.26 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
'use strict';
var PORT = process.env.PORT || 9100;
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 sendAllUsers(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: 'There are total of ' + users.length + ' users online in this room. \n' +
'List of all users: ' + users.join(', '),
timestamp: moment().valueOf()
});
}
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: 'System',
text: userData.name + ' has left the room.',
timestamp: moment().valueOf()
});
delete clientInfo[socket.id];
}
});
socket.on('join-room', function (request) {
clientInfo[socket.id] = request;
socket.join(request.room);
socket.broadcast.to(request.room).emit('message', {
name: 'System',
text: request.name + ' has joined the room!',
timestamp: moment().valueOf()
});
});
socket.on('message', function (message) {
if(message.text === '@users') {
sendAllUsers(socket);
} else {
message.timestamp = moment().valueOf();
io.to(clientInfo[socket.id].room).emit('message', message);
}
});
socket.emit('message', {
name: 'System',
text: 'Welcome to the chat application!',
timestamp: moment().valueOf()
});
});
http.listen(PORT, function () {
console.log('Server started at port ' + PORT);
})