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