File size: 4,641 Bytes
3162254
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
import http from "http";
import path from "path";
import express from "express";
import process from "process";
import { Server } from "socket.io";
import type { ServerHandler, ClientHandler, SocketEventParams } from "../types/websocket";
import { CLINT_EVENT, SERVER_EVENT } from "../types/websocket";
import type { Member, ServerSocket } from "../types/server";
import { CONNECTION_STATE, ERROR_TYPE } from "../types/server";
import { getLocalIp, updateMember } from "./utils";

const app = express();
app.use(express.static(path.resolve(__dirname, "static")));
const httpServer = http.createServer(app);
const io = new Server<ClientHandler, ServerHandler>(httpServer);

const authenticate = new WeakMap<ServerSocket, string>();
const room = new Map<string, Member>();
const peer = new Map<string, string>();

io.on("connection", socket => {
  socket.on(CLINT_EVENT.JOIN_ROOM, ({ id, device }) => {
    // 验证
    if (!id) return void 0;
    authenticate.set(socket, id);
    // 房间通知消息
    const initialization: SocketEventParams["JOINED_MEMBER"]["initialization"] = [];
    room.forEach((instance, key) => {
      initialization.push({ id: key, device: instance.device });
      instance.socket.emit(SERVER_EVENT.JOINED_ROOM, { id, device });
    });
    // 加入房间
    room.set(id, { socket, device, state: CONNECTION_STATE.READY });
    socket.emit(SERVER_EVENT.JOINED_MEMBER, { initialization });
  });

  socket.on(CLINT_EVENT.SEND_REQUEST, ({ origin, target }, cb) => {
    // 验证
    if (authenticate.get(socket) !== origin) return void 0;
    // 转发`Request`
    const member = room.get(target);
    if (member) {
      if (member.state !== CONNECTION_STATE.READY) {
        cb?.({ code: ERROR_TYPE.PEER_BUSY, message: `Peer ${target} is Busy` });
        return void 0;
      }
      updateMember(room, origin, "state", CONNECTION_STATE.CONNECTING);
      member.socket.emit(SERVER_EVENT.FORWARD_REQUEST, { origin, target });
    } else {
      cb?.({ code: ERROR_TYPE.PEER_NOT_FOUND, message: `Peer ${target} Not Found` });
    }
  });

  socket.on(CLINT_EVENT.SEND_RESPONSE, ({ origin, code, reason, target }) => {
    // 验证
    if (authenticate.get(socket) !== origin) return void 0;
    // 转发`Response`
    const targetSocket = room.get(target)?.socket;
    if (targetSocket) {
      updateMember(room, origin, "state", CONNECTION_STATE.CONNECTED);
      updateMember(room, target, "state", CONNECTION_STATE.CONNECTED);
      peer.set(origin, target);
      peer.set(target, origin);
      targetSocket.emit(SERVER_EVENT.FORWARD_RESPONSE, { origin, code, reason, target });
    }
  });

  socket.on(CLINT_EVENT.SEND_MESSAGE, ({ origin, message, target }) => {
    // 验证
    if (authenticate.get(socket) !== origin) return void 0;
    // 转发`Message`
    const targetSocket = room.get(target)?.socket;
    if (targetSocket) {
      targetSocket.emit(SERVER_EVENT.FORWARD_MESSAGE, { origin, message, target });
    }
  });

  socket.on(CLINT_EVENT.SEND_UNPEER, ({ origin, target }) => {
    // 验证
    if (authenticate.get(socket) !== origin) return void 0;
    // 处理自身的状态
    peer.delete(origin);
    updateMember(room, origin, "state", CONNECTION_STATE.READY);
    // 验证
    if (peer.get(target) !== origin) return void 0;
    // 转发`Unpeer`
    const targetSocket = room.get(target)?.socket;
    if (targetSocket) {
      // 处理`Peer`状态
      updateMember(room, target, "state", CONNECTION_STATE.READY);
      peer.delete(target);
      targetSocket.emit(SERVER_EVENT.FORWARD_UNPEER, { origin, target });
    }
  });

  const onLeaveRoom = () => {
    // 验证
    const id = authenticate.get(socket);
    if (id) {
      const peerId = peer.get(id);
      peer.delete(id);
      if (peerId) {
        // 状态复位
        peer.delete(peerId);
        updateMember(room, peerId, "state", CONNECTION_STATE.READY);
      }
      // 退出房间
      room.delete(id);
      room.forEach(instance => {
        instance.socket.emit(SERVER_EVENT.LEFT_ROOM, { id });
      });
    }
  };

  socket.on(CLINT_EVENT.LEAVE_ROOM, onLeaveRoom);
  socket.on("disconnect", onLeaveRoom);
});

process.on("SIGINT", () => {
  console.info("SIGINT Received, exiting...");
  process.exit(0);
});

process.on("SIGTERM", () => {
  console.info("SIGTERM Received, exiting...");
  process.exit(0);
});

const PORT = Number(process.env.PORT) || 3000;
httpServer.listen(PORT, () => {
  const ip = getLocalIp();
  console.log(`Listening on port http://localhost:${PORT} ...`);
  ip.forEach(item => {
    console.log(`Listening on port http://${item}:${PORT} ...`);
  });
});