-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
81 lines (60 loc) · 2.2 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
const path = require('path');
const http = require('http');
const express = require('express');
const scoketio = require('socket.io');
const formatMessage = require('./utils/messages');
const {
userJoin,
getCurrentUser,
getRoomUsers,
userleaves
} = require('./utils/users');
const app = express();
const server = http.createServer(app);
const io = scoketio(server);
const PORT = process.env.PORT || 3000;
// set a static folder
app.use(express.static(path.join(__dirname, 'public')));
const botName = '';
//run when a client join
io.on('connection', socket => {
// console.log('new connection ..');
//username and room comes from main.js
socket.on('joinRoom', ({
username,
room
}) => {
const user = userJoin(socket.id, username, room);
socket.join(user.room);
//sents to the frontend main.js file when new user connects (only for the user)
// socket.emit('message', formatMessage(botName, 'Welcome to chat !'));
socket.emit('messageFromBot', formatMessage(botName, 'Welcome to chat !'));
//brodcast when a user connects (all users execpt joined one )
socket.broadcast.to(user.room).emit('messageFromBot', formatMessage(botName, `${user.username} has joined the chat`));
//send users and room info
io.to(user.room).emit('roomUsers', {
room :user.room,
users: getRoomUsers(user.room)
});
});
// listen for chat message
socket.on('chatMessage', msg => {
// console.log(msg);
const user = getCurrentUser(socket.id);
// (io.emit ) for all users
io.to(user.room).emit('message', formatMessage(user.username, msg));
});
// when a user left the chat
socket.on('disconnect', () => {
const user = userleaves(socket.id);
if(user){
io.to(user.room).emit('messageFromBot', formatMessage(botName, `${user.username} has left the chat`));
//send users and room info
io.to(user.room).emit('roomUsers', {
room :user.room,
users: getRoomUsers(user.room)
});
}
});
});
server.listen(PORT, () => console.log(`server running on PORT : ${PORT}`));