server.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. //server.js 專案起始點
  2. const WebSocket = require('ws');
  3. const http = require('http');
  4. const express = require("express");
  5. const cookieSession = require("cookie-session");
  6. const dotenv = require('dotenv').config();
  7. const db = require('./pass_db.js');
  8. db.users_init_fixed()
  9. db.vote_init_random(5); // you COULD change this, but you could also leave it alone?
  10. const app = express();
  11. const server = http.createServer(app);
  12. const PORT = process.env.PORT || 8000; // 允許從 .env 文件或環境變量中設定端口
  13. app.use(express.static("static"))
  14. app.set('view engine', 'ejs')
  15. app.use(cookieSession({
  16. name: 'session',
  17. keys: [process.env.SESSION_KEY || 'default_session_key'],
  18. maxAge: 24 * 60 * 60 * 1000 // 24 hours
  19. }))
  20. // 使用 Express 內建的中間件來解析 JSON 和 URL 編碼的資料
  21. app.use(express.json());
  22. app.use(express.urlencoded({ extended: true }));
  23. const apiRouter = require("./routers/api")
  24. app.use('/api/v1', apiRouter);
  25. // app.listen(PORT, () => console.log(`server should be running at http://localhost:${PORT}/`))
  26. const wss = new WebSocket.Server({ server });
  27. global.wss = wss; //fix it future
  28. wss.on('connection', ws => {
  29. console.log('New WebSocket connection');
  30. ws.on('message', message => {
  31. console.log(`Received message: ${message}`);
  32. // 廣播消息給所有連接的客戶端
  33. wss.clients.forEach(client => {
  34. if (client !== ws && client.readyState === WebSocket.OPEN) {
  35. client.send(message);
  36. }
  37. });
  38. });
  39. });
  40. server.listen(PORT, () => console.log(`Server is running at http://localhost:${PORT}/`));