-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
67 lines (49 loc) · 2.24 KB
/
server.js
File metadata and controls
67 lines (49 loc) · 2.24 KB
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
const path = require('path');
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const formatMessage = require('./utils/messages');
const { userJoin, getCurrentUser, userLeave, getRoomUsers } = require('./utils/users');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
// Set static folder - (set 'public' as a static folder to access the frontend)
app.use(express.static(path.join(__dirname, "public")));
const botName = 'ChatCord Bot';
// Run when client connects
io.on('connection', socket => {
// console.log('New WS Connection...') // WS - Web Socket
socket.on('joinRoom', ({ username, room }) => {
const user = userJoin(socket.id, username, room);
socket.join(user.room);
// Welcome current user
socket.emit('message', formatMessage(botName, 'Welcome to ChatCord!')); // Message to the single client
// Broadcast when a user connects - message to others that a user has joined except to the user itself
socket.broadcast.to(user.room).emit('message', formatMessage(botName, `${user.username} has joined the chat`)); // used -> .to(user.room) to get the message in a specific room the user joint
// Sent userrs and room info
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getRoomUsers(user.room)
});
})
// Listen for chatMessage
socket.on('chatMessage', msg => {
const user = getCurrentUser(socket.id);
io.to(user.room).emit('message', formatMessage(user.username, msg));
});
// Runs when client disconnects
socket.on('disconnect', () => {
const user = userLeave(socket.id);
// Send message to the specific room the user was in
if (user) {
io.to(user.room).emit('message', formatMessage(botName, `${user.username} has left the chat`)); // message to all the clients in general
// Sent users and room info
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getRoomUsers(user.room)
});
};
})
})
const PORT = 3000 || process.env.PORT;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));