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