-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
89 lines (73 loc) · 2.75 KB
/
Copy pathserver.js
File metadata and controls
89 lines (73 loc) · 2.75 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
const express = require("express");
const app = express();
const http = require("http").createServer(app);
const io = require("socket.io")(http);
const bodyParser = require('body-parser');
const methodOverride = require('method-override');
const session = require('express-session');
const dotenv = require('dotenv'); // Import dotenv
const path = require('path');
dotenv.config();
app.use('/socket.io', express.static(path.join(__dirname, 'node_modules/socket.io/client-dist')));
app.use(bodyParser.urlencoded({ extended: true }));
app.set('view engine', 'ejs');
app.set('views', 'app/views');
app.use(express.static('app/public'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(methodOverride('_method', { methods: ['POST', 'GET'] }));
app.use(methodOverride(function (req, res) {
if (req.body && typeof req.body === 'object' && '_method' in req.body) {
var method = req.body._method;
delete req.body._method;
return method;
}
}));
app.use(session({
secret: process.env.SESSION_SECRET || 'your_secret_key', // Ensure SESSION_SECRET is defined or provide a default
resave: true,
saveUninitialized: true,
}));
const users = {};
io.on('connection', (socket) => {
console.log('A user connected');
socket.on('join', ({ userId, courseId, username }) => {
if (!users[courseId]) {
users[courseId] = [];
}
users[courseId].push({ userId, socketId: socket.id, username });
socket.join(courseId);
io.to(courseId).emit('user connected', `${username} has joined the chat`);
console.log(`User ${username} connected to course ${courseId}`);
});
socket.on('chat message', ({ userId, courseId, msg }) => {
const user = users[courseId].find(user => user.userId === userId);
if (user) {
io.to(courseId).emit('chat message', { username: user.username, msg });
}
});
socket.on('disconnect', () => {
let userCourseId = null;
let username = null;
for (const courseId in users) {
const userIndex = users[courseId].findIndex(user => user.socketId === socket.id);
if (userIndex !== -1) {
userCourseId = courseId;
username = users[courseId][userIndex].username;
users[courseId].splice(userIndex, 1);
break;
}
}
if (userCourseId && username) {
io.to(userCourseId).emit('user disconnected', `${username} has left the chat`);
}
console.log('A user disconnected');
});
});
require('./app/routes/route')(app);
app.get("/", (req, res) => {
res.render("home");
});
http.listen(3000, function() {
console.log('Server running: http://localhost:3000');
});