|
| 1 | +"use strict"; |
| 2 | + |
| 3 | +const session = require("express-session"); |
| 4 | +const express = require("express"); |
| 5 | +const http = require("http"); |
| 6 | +const uuid = require("uuid"); |
| 7 | + |
| 8 | +const { WebSocketManager } = require("./websocketManager.js"); |
| 9 | +WebSocketManager.prototype.init(); |
| 10 | + |
| 11 | +const websockerInstance = WebSocketManager.prototype.getInstance(); |
| 12 | + |
| 13 | +websockerInstance.addClientStatusChangeListener((client, status) => { |
| 14 | + if (status === "open") { |
| 15 | + websockerInstance.sendMessage(client, { |
| 16 | + type: "hello", |
| 17 | + data: { deviceId: client.deviceId } |
| 18 | + }); |
| 19 | + } |
| 20 | +}); |
| 21 | + |
| 22 | +websockerInstance.addClientMessageListener((client, data) => { |
| 23 | + console.log("🚀 ~ file: index.js:16 ~ WebSocketManager.prototype.getInstance ~ client:", client); |
| 24 | + try { |
| 25 | + const messageObj = JSON.parse(data); |
| 26 | + const action = messageObj.action; |
| 27 | + |
| 28 | + if (action == "register") { |
| 29 | + // 注册设备 |
| 30 | + const { deviceId } = messageObj.data; |
| 31 | + if (!deviceId) { |
| 32 | + ws.send(sendMsg({ code: 400, message: "deviceId 不能为空" })); |
| 33 | + return; |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + if (action == "broadCase") { |
| 38 | + // 触发消息广播 |
| 39 | + websockerInstance.broadcast("我是广播消息"); |
| 40 | + } |
| 41 | + } catch (error) { |
| 42 | + console.error("🚀 ~ file: index.js:89 ~ error:", error); |
| 43 | + console.log(`从用户 接收到消息 ${data}`); |
| 44 | + } |
| 45 | +}); |
| 46 | + |
| 47 | +const app = express(); |
| 48 | +const mapSocket = new Map(); |
| 49 | + |
| 50 | +const sessionParser = session({ |
| 51 | + saveUninitialized: false, |
| 52 | + secret: "$eCuRiTy", |
| 53 | + resave: false |
| 54 | +}); |
| 55 | + |
| 56 | +app.use(express.static(__dirname + "/public")); |
| 57 | +app.use(sessionParser); |
| 58 | + |
| 59 | +app.post("/login", function (req, res) { |
| 60 | + const id = uuid.v4(); |
| 61 | + |
| 62 | + console.log(`更新用户 ${id} 的会话`); |
| 63 | + req.session.userId = id; |
| 64 | + res.send({ result: "OK", message: "会话已更新" }); |
| 65 | +}); |
| 66 | + |
| 67 | +app.delete("/logout", function (request, response) { |
| 68 | + const ws = mapSocket.get(request.session.userId); |
| 69 | + |
| 70 | + console.log("销毁会话"); |
| 71 | + request.session.destroy(function () { |
| 72 | + if (ws) ws.close(); |
| 73 | + |
| 74 | + response.send({ result: "OK", message: "会话已销毁" }); |
| 75 | + }); |
| 76 | +}); |
| 77 | + |
| 78 | +const server = http.createServer(app); |
| 79 | +server.listen(8090, function () { |
| 80 | + console.log("正在监听 http://localhost:8090"); |
| 81 | +}); |
| 82 | + |
| 83 | +const sendMsg = (data = {}, type = "json") => { |
| 84 | + return JSON.stringify({ |
| 85 | + type, |
| 86 | + data |
| 87 | + }); |
| 88 | +}; |
0 commit comments