-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
53 lines (40 loc) · 1.67 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
const express = require('express');
const path = require('path');
const http = require('http');
const formatMsg = require('./utils/messages');
const { joinUser, getCurrentuser, userLeave, getRoomUsers } = require('./utils/users')
const app = express();
const server = http.createServer(app);
const io = require('socket.io')(server);
const bot = 'ChatBook Bot';
io.on('connection', socket => {
socket.on('join-room', ({ name, room }) => {
const user = joinUser(socket.id, name, room);
socket.join(user.room);
socket.emit('message', formatMsg(bot, 'Welcome to Messenger.'));
socket.on('new-user-Join', () => {
socket.broadcast.to(user.room).emit('message', formatMsg(bot, `${user.name} has joined the chat`));
});
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getRoomUsers(user.room)
});
});
socket.on('chatMsg', (msg) => {
const user = getCurrentuser(socket.id);
socket.broadcast.to(user.room).emit('message', formatMsg(user.name, msg))
});
socket.on('disconnect', () => {
const user = userLeave(socket.id);
if(user){
socket.broadcast.to(user.room).emit('message', formatMsg(bot, `${user.name} has left the chat`))
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getRoomUsers(user.room)
});
}
});
});
app.use(express.static(path.join(__dirname, 'public')));
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => console.log(`Server is running on port ${PORT}`));