-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
73 lines (58 loc) · 2.16 KB
/
server.js
File metadata and controls
73 lines (58 loc) · 2.16 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
68
69
70
71
72
73
import express from "express";
import http from "http";
import cors from "cors"
import { Server } from 'socket.io';
import path from "path";
import { fileURLToPath } from 'url';
import { formatMessage } from "./utils/message.js";
import { userJoin, getCurrentUser, userLeave, getRoomUsers } from "./utils/users.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
const server = http.createServer(app);
const io = new Server(server);
const botName = "PixelBot";
// Serve static files from the 'public' directory
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors());
app.use((req, res, next) => {
res.setHeader("X-Frame-Options", "ALLOWALL");
next();
});
// Run when a client connects
io.on('connection', socket => {
socket.on("joinRoom", ({ username, room }) => {
const user = userJoin(socket.id, username, room);
socket.join(user.room);
// Welcome the current user
socket.emit('message', formatMessage(botName, 'Welcome To JustChat!'));
// Broadcast when a user connects
socket.broadcast.to(user.room).emit('message', formatMessage(botName, `${user.username} has joined the chat`));
// Send user's and room info
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getRoomUsers(user.room)
});
});
// Listen for chatMessage from frontend
socket.on('chatMessage', msg => {
const user = getCurrentUser(socket.id);
io.to(user.room).emit('message', formatMessage(user.username, msg));
});
// Runs when a client disconnects
socket.on('disconnect', () => {
const user = userLeave(socket.id);
if (user) {
io.to(user.room).emit('message', formatMessage(botName, `${user.username} has left the chat`));
// Send user's and room info
io.to(user.room).emit('roomUsers', {
room: user.room,
users: getRoomUsers(user.room)
});
}
});
});
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server is running on ${PORT}`);
});