-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
56 lines (49 loc) · 1.88 KB
/
index.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
const express = require('express');
const path = require('path');
const http = require('http');
const socketio = require('socket.io');
const formatMessage = require('./utils/messages');
const {userJoin, getCurrentUser, removeuser, getusersinroom} = require('./utils/users');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
// Set the Front end static folder
app.use(express.static(path.join(__dirname, 'public')));
const PORT = process.env.PORT || 3000;
// Run when client connects
io.on('connection', socket => {
// Join to chatRoom
socket.on('joinRoom', ({ username, room }) => {
const user = userJoin(socket.id, username, room);
socket.join(room);
// Welcome current user
socket.emit('message', formatMessage('ChatCord Bot', 'Welcome to ChatCord!'));
// Broadcast when a user connects
socket.broadcast.to(user.room).emit('message', formatMessage('ChatCord Bot', `${username} has joined the chat`));
// Send users and room info
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getusersinroom(user.room)
});
});
// Runs when client disconnects
socket.on('disconnect', () => {
const user = removeuser(socket.id);
if (user) {
io.to(user.room).emit('message', formatMessage('ChatCord Bot', `${user.username} has left the chat`));
// Send users and room info
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getusersinroom(user.room)
});
}
})
// Listen for chatMessage
socket.on('chatMessage', msg => {
const user = getCurrentUser(socket.id);
io.to(user.room).emit('message', formatMessage(user.username, msg));
})
})
server.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});