-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
94 lines (67 loc) · 2.39 KB
/
app.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
92
93
94
const http = require('http');
const express = require('express');
const {
static
} = require('express');
const {
disconnect
} = require('process');
//getting utils
const formatMsg = require('./utils/message');
const {
userJoin,
getCurrentUser,
userLeave,
getGrpUsers
} = require('./utils/user');
const botName = "Chat Bot"
const app = express();
const server = http.createServer(app);
//passing server inside socket to make WEBSOCKET
const io = require('socket.io')(server);
//Access to the Static files
app.use(express.static(__dirname + '/static'));
app.use(express.static(__dirname + '/view'));
app.use('/', (req, res, next) => {
res.sendFile(__dirname + '/view/index.html');
});
//Starting socket connections
io.on('connection', (socket) => {
//Join the room and handle to send message to specific grp
socket.on('JoinGrp', ({
username,
grp
}) => {
const user = userJoin(socket.id, username, grp);
//join the respective grp using socket.join
socket.join(user.grp);
//Welcome event
socket.emit('recieve', formatMsg(botName, "Welcome to Chat!"));
// Broadcast when user enter or leave
socket.broadcast.to(user.grp).emit('recieve', formatMsg(botName, `${user.username} has joined the chat`));
io.to(user.grp).emit("grpUser", {
grp: user.grp,
users: getGrpUsers(user.grp)
});
});
// Grabing msg from dom and emiting it to client.js to give output
socket.on('message', (msg) => {
const user = getCurrentUser(socket.id);
socket.emit('message', formatMsg(user.username, msg));
// Brodcast msg to all other user which append on left
socket.broadcast.to(user.grp).emit('recieve', formatMsg(user.username, msg));
});
// Disconnect the socket when user leave
socket.on('disconnect', (msg) => {
const user = userLeave(socket.id);
if (user) {
io.to(user.grp).emit('recieve', formatMsg(botName, `${user.username} has Left the chat`));
io.to(user.grp).emit("grpUser", {
grp: user.grp,
users: getGrpUsers(user.grp)
});
}
});
});
const PORT = 3000 || process.env.PORT;
server.listen(PORT, () => console.log(`Running on port`, PORT));