-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
227 lines (193 loc) · 5.78 KB
/
server.js
File metadata and controls
227 lines (193 loc) · 5.78 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
const express = require("express")
const { createServer } = require("http")
const { Server } = require("socket.io")
const cors = require("cors")
const app = express()
app.use(
cors({
origin: "*", // Allow all origins for flexibility
methods: ["GET", "POST"],
credentials: true,
}),
)
app.use(express.json())
const server = createServer(app)
const io = new Server(server, {
cors: {
origin: "*",
methods: ["GET", "POST"],
credentials: true,
},
})
// In-memory storage
let currentPoll = null
const students = new Map()
const pollHistory = []
const chatMessages = []
let pollTimer = null
io.on("connection", (socket) => {
console.log("User connected:", socket.id)
// Student joins - IMMEDIATE broadcast
socket.on("join-as-student", ({ name }) => {
console.log("👤 Student joining:", name)
const student = {
id: socket.id,
name,
hasAnswered: false,
isOnline: true,
joinedAt: new Date().toISOString(),
}
students.set(socket.id, student)
// IMMEDIATE broadcast to all clients
io.emit("student-joined", student)
io.emit("students-list", Array.from(students.values()))
console.log("📢 Student joined - immediate broadcast sent")
// Send current poll if active
if (currentPoll && currentPoll.isActive) {
socket.emit("poll-created", currentPoll)
}
// Send chat history
socket.emit("chat-history", chatMessages)
})
socket.on("get-current-poll", () => {
if (currentPoll && currentPoll.isActive) {
socket.emit("poll-created", currentPoll)
}
})
// Teacher creates poll
socket.on("create-poll", (poll) => {
console.log("🎯 Creating new poll:", poll.question)
// Clear any existing timer
if (pollTimer) {
clearInterval(pollTimer)
pollTimer = null
}
currentPoll = {
...poll,
results: {},
totalVotes: 0,
}
// Reset all students' answer status
students.forEach((student) => {
student.hasAnswered = false
})
// Broadcast poll to all clients
io.emit("poll-created", currentPoll)
io.emit("students-list", Array.from(students.values()))
// Start timer
let timeLeft = poll.timeLimit
io.emit("poll-time-update", timeLeft)
pollTimer = setInterval(() => {
timeLeft--
io.emit("poll-time-update", timeLeft) // This should continue for ALL clients
if (timeLeft <= 0) {
clearInterval(pollTimer)
pollTimer = null
currentPoll.isActive = false
pollHistory.unshift({ ...currentPoll })
io.emit("poll-ended")
io.emit("poll-history", pollHistory)
}
}, 1000)
})
// Student submits answer - STOP TIMER when all answered
socket.on("submit-answer", ({ pollId, answer }) => {
if (!currentPoll || currentPoll.id !== pollId || !currentPoll.isActive) {
return
}
const student = students.get(socket.id)
if (!student || student.hasAnswered) {
return
}
// Mark student as answered
student.hasAnswered = true
students.set(socket.id, student)
// Update poll results
currentPoll.results[answer] = (currentPoll.results[answer] || 0) + 1
currentPoll.totalVotes++
// Broadcast updated results
io.emit("poll-answer", { studentId: socket.id, answer })
io.emit("poll-results-updated", currentPoll.results)
io.emit("students-list", Array.from(students.values()))
// Check if all students have answered - STOP TIMER IMMEDIATELY
const allAnswered = Array.from(students.values()).every((s) => s.hasAnswered)
if (allAnswered && students.size > 0) {
console.log("🏁 All students answered - stopping timer")
if (pollTimer) {
clearInterval(pollTimer)
pollTimer = null
}
currentPoll.isActive = false
pollHistory.unshift({ ...currentPoll })
io.emit("poll-ended")
io.emit("poll-history", pollHistory)
} else {
// Timer continues running for remaining students
console.log(
`⏰ Timer continues - ${Array.from(students.values()).filter((s) => !s.hasAnswered).length} students still need to answer`,
)
}
})
// Clear poll
socket.on("clear-poll", () => {
if (pollTimer) {
clearInterval(pollTimer)
pollTimer = null
}
currentPoll = null
io.emit("clear-poll")
})
// Teacher kicks student
socket.on("kick-student", (studentId) => {
if (students.has(studentId)) {
io.to(studentId).emit("kicked")
students.delete(studentId)
io.emit("student-left", studentId)
io.emit("students-list", Array.from(students.values()))
const studentSocket = io.sockets.sockets.get(studentId)
if (studentSocket) {
studentSocket.disconnect()
}
}
})
// Chat functionality
socket.on("send-chat-message", (message) => {
chatMessages.push(message)
if (chatMessages.length > 100) {
chatMessages.shift()
}
io.emit("chat-message", message)
})
socket.on("get-poll-history", () => {
socket.emit("poll-history", pollHistory)
})
// Handle disconnect - IMMEDIATE update
socket.on("disconnect", () => {
console.log("User disconnected:", socket.id)
if (students.has(socket.id)) {
students.delete(socket.id)
io.emit("student-left", socket.id)
io.emit("students-list", Array.from(students.values()))
}
})
})
// API routes
app.get("/", (req, res) => {
res.json({
message: "Live Polling System Socket Server",
status: "running",
timestamp: new Date().toISOString(),
})
})
app.get("/health", (req, res) => {
res.json({
status: "healthy",
timestamp: new Date().toISOString(),
uptime: process.uptime(),
connectedStudents: students.size,
})
})
const PORT = process.env.PORT || 3001
server.listen(PORT, "0.0.0.0", () => {
console.log(`🚀 Socket.io server running on port ${PORT}`)
})