server.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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); //把express透過http createServer
  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 }); //server的資訊拿去架設websocket
  27. global.wss = wss; //fix it future 把wss設定存放到global供其他js檔案存取 PS:寫成global不是很好的做法 你可以考慮替換成更好的方法?
  28. wss.on('connection', ws => { //建立連線
  29. console.log('New WebSocket connection'); //提示server端成功建立連線
  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}/`));