-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
259 lines (210 loc) Β· 7.58 KB
/
server.js
File metadata and controls
259 lines (210 loc) Β· 7.58 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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
const path = require('path');
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const { io: ClientIO } = require('socket.io-client');
const axios = require('axios');
const IS_PRODUCTION = process.env.ENV || 'production' === 'production';
console.log(IS_PRODUCTION);
const PORT = process.env.PORT || 3000;
const PUBLISHER_URL = 'http://localhost:3000';
const app = express();
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: '*',
methods: ['GET', 'POST'],
},
});
// β
Serve React build files (only in production)
if (IS_PRODUCTION) {
app.use(express.static(path.join(__dirname, './build')));
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, './build/index.html'));
});
} else {
app.get('*', (req, res) => {
res.send('React app is running in development mode.');
});
}
console.log(process.env.PORT);
if (Number(PORT) === 3000) {
console.log('Running as HOST (Publisher)');
let countdown = 60;
let nextCountdown = 15;
let interval = null; // Store interval reference
const appState = {
potMoney: null,
winningNumbers: null,
}
const startCountdown = () => {
interval = setInterval(async () => {
try {
if (countdown > 0) {
countdown--;
} else {
console.log("π Time's up! Fetching draw results...");
// β
Fetch draw results from API
const { data } = await axios.post("http://localhost:8000/v1/draw/", {}, {
headers: { apikey: "nigga" }
});
console.log("π― Draw Result:", data);
appState.winningNumbers = data.data.winning_no;
// β
Broadcast draw result to subscribers
io.emit("draw_result", data);
// β
Reset countdown for the next round
countdown = nextCountdown;
setTimeout(() => {
console.log("π New round starting...");
countdown = 60;
}, nextCountdown * 1000);
}
// β
Broadcast updated results of the appState
io.emit("app_state_update_pot_money", appState.potMoney);
io.emit("app_state_update_draw_number", appState.winningNumbers);
io.emit("countdown", countdown);
} catch (error) {
console.error("β Server Error: ", error.message);
shutdownServer("Server error occurred. Shutting down...");
}
}, 1000);
};
startCountdown();
const fetchPotAmount = async () => {
try {
const { data } = await axios.get("http://localhost:8000/v1/pot/", {
headers: {
apikey: "nigga",
},
});
console.log("π° Pot Amount:", data);
appState.potMoney = data.data.amount.pot_amount
// β
Emit pot amount to subscribers
io.emit("pot_update", data);
} catch (error) {
console.error("β Failed to fetch pot amount:", error.message);
}
};
// β
Call fetchPotAmount every 10 seconds
setInterval(fetchPotAmount, 10000);
/**
* π Graceful Shutdown Function
*/
function shutdownServer(reason) {
console.log(`π ${reason}`);
io.emit("shutdown");
clearInterval(interval);
io.close();
process.exit(1);
}
process.on("uncaughtException", (err) => {
console.error("β οΈ Uncaught Exception:", err);
shutdownServer("Unexpected server error!");
});
process.on("unhandledRejection", (reason, promise) => {
console.error("β οΈ Unhandled Promise Rejection:", reason);
shutdownServer("Unhandled promise rejection!");
});
// const onlineUsers = new Map();
// io.on("connection", (socket) => {
// console.log(`Subscriber connected to Publisher: ${socket.id}`);
// console.log(onlineUsers)
// socket.on("user_online", (username) => {
// console.log(username)
// if (username && username !== "Guest") {
// onlineUsers.add(username);
// console.log("π₯ Emitting online_users event:", Array.from(onlineUsers.values()));
// io.emit("online_users", Array.from(onlineUsers));
// console.log("π₯ Online Users:", onlineUsers);
// }
// });
// socket.on("place_bet", (betData) => {
// console.log("Received bet from subscriber:", betData);
// // β
Broadcast bet to all subscribers
// io.emit("new_bet", betData);
// });
// socket.on("disconnect", () => {
// console.log(`Subscriber disconnected: ${socket.id}`);
// onlineUsers.forEach((user) => {
// if (socket.id === user.socketId) {
// onlineUsers.delete(user);
// }
// });
// io.emit("online_users", Array.from(onlineUsers));
// });
// });
} else {
let isPublisherConnected = false;
const publisherSocket = ClientIO(PUBLISHER_URL);
publisherSocket.on("connect", () => {
console.log(`β
Subscriber (${PORT}) connected to Publisher (3000)`);
isPublisherConnected = true;
});
publisherSocket.on("disconnect", () => {
console.log(`β οΈ Publisher (3000) disconnected! Stopping data emission.`);
isPublisherConnected = false;
io.emit("maintenance_mode", true);
});
publisherSocket.on("shutdown", () => {
console.log(`π Publisher sent shutdown signal!`);
isPublisherConnected = false;
io.emit("maintenance_mode", true);
});
// Listen for draw results from Publisher
publisherSocket.on('countdown', (data) => {
if (isPublisherConnected) {
console.log(`Subscriber (${PORT}) received countdown:, ${data}`);
io.emit('countdown', data); // β
Only emit if publisher is connected
}
});
publisherSocket.on('draw_result', (data) => {
if (isPublisherConnected) {
console.log(`Subscriber (${PORT}) received draw_result:, ${data}`);
io.emit('draw_result', data); // β
Only emit if publisher is connected
}
});
publisherSocket.on('pot_update', (data) => {
if (isPublisherConnected) {
console.log(`Subscriber (${PORT}) received pot_update:, ${data}`);
io.emit('pot_update', data); // β
Only emit if publisher is connected
}
});
publisherSocket.on('app_state_update_pot_money', (data) => {
if (isPublisherConnected) {
console.log(`Subscriber (${PORT}) received app_state_update:, ${data}`);
io.emit('app_state_update_pot_money', data); // β
Only emit if publisher is connected
}
});
publisherSocket.on('app_state_update_draw_number', (data) => {
if (isPublisherConnected) {
console.log(`Subscriber (${PORT}) received app_state_update:, ${data}`);
io.emit('app_state_update_draw_number', data); // β
Only emit if publisher is connected
}
});
// Handle client connections
io.on('connection', (socket) => {
console.log(`Client connected to Subscriber (${PORT}): ${socket.id}`);
// If publisher is disconnected, immediately inform client
if (!isPublisherConnected) {
socket.emit("maintenance_mode", true);
}
// β
Listen for user bets and forward them to the publisher
socket.on("place_bet", (betData) => {
console.log(`Received bet from client:`, betData);
if (isPublisherConnected) {
publisherSocket.emit("place_bet", betData);
}
});
socket.on("disconnect", () => {
console.log(`Client disconnected from Subscriber (${PORT}): ${socket.id}`);
});
});
// β
Receive new bets from Publisher and forward to clients
publisherSocket.on("new_bet", (betData) => {
console.log("New bet received from Publisher:", betData);
io.emit("new_bet", betData);
});
}
server.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});