diff --git a/apps/server/src/Core/MyServer.ts b/apps/server/src/Core/MyServer.ts index 15707d5..45b3fd2 100644 --- a/apps/server/src/Core/MyServer.ts +++ b/apps/server/src/Core/MyServer.ts @@ -1,10 +1,10 @@ -import { EventEmitter } from "stream"; -import WebSocket, { WebSocketServer } from "ws"; -import { ApiMsgEnum } from "../Common"; -import { Connection, ConnectionEventEnum } from "./Connection"; +import { EventEmitter } from "stream" +import WebSocket, { WebSocketServer } from "ws" +import { ApiMsgEnum, IModel } from "../Common" +import { Connection, ConnectionEventEnum } from "./Connection" export interface IMyServerOptions { - port: number; + port: number } export enum MyServerEventEnum { @@ -13,51 +13,51 @@ export enum MyServerEventEnum { } export class MyServer extends EventEmitter { - wss?: WebSocketServer; - port: number; - connections: Set = new Set(); - apiMap: Map = new Map(); + wss?: WebSocketServer + port: number + connections: Set = new Set() + apiMap: Map = new Map() constructor({ port = 8080 }: Partial) { - super(); - this.port = port; + super() + this.port = port } start() { return new Promise((resolve, reject) => { - this.wss = new WebSocketServer({ port: this.port }); - this.wss.on("connection", this.handleConnect.bind(this)); + this.wss = new WebSocketServer({ port: this.port }) + this.wss.on("connection", this.handleConnect.bind(this)) this.wss.on("error", (e) => { - reject(e); - }); + reject(e) + }) this.wss.on("close", () => { - console.log("MyServer 服务关闭"); - }); + console.log("MyServer 服务关闭") + }) this.wss.on("listening", () => { - resolve(true); - }); - }); + resolve(true) + }) + }) } handleConnect(ws: WebSocket) { //初始化 - const connection = new Connection(this, ws); + const connection = new Connection(this, ws) //向外告知有人来了 - this.connections.add(connection); - this.emit(MyServerEventEnum.Connect, connection); + this.connections.add(connection) + this.emit(MyServerEventEnum.Connect, connection) //向外告知有人走了 connection.on(ConnectionEventEnum.Close, (code: number, reason: string) => { - this.connections.delete(connection); - this.emit(MyServerEventEnum.DisConnect, connection, code, reason); - }); + this.connections.delete(connection) + this.emit(MyServerEventEnum.DisConnect, connection, code, reason) + }) } - setApi(apiName: ApiMsgEnum, cb: Function) { - this.apiMap.set(apiName, cb); + setApi(name: T, cb: (connection: Connection, args: IModel["api"][T]["res"]) => void) { + this.apiMap.set(name, cb) } }