堆栈: Node.js + Express + TypeScript + Socket.io + tsyringe
架构:有一个WebServer
类创建套接字连接,然后将io
和socket
对象传递给SocketController
类。这两个类都被装饰了,@singleton()
并且WebServer
该类在一个名为 的顶级静态函数中解析main
。
问题:多次调用套接字方法后,发射过程(响应套接字上的侦听方法)多次发生。每次调用该方法时,它实际上都会递增。但是控制器中的实际逻辑每次调用只执行一次。
代码:
顶级模块:
class Program {
static Main(): void {
const webServer = container.resolve(WebServer);
const httpServer = webServer.StartServer();
webServer.SocketConnection(httpServer);
}
}
Program.Main();
WebServer
班级:
@singleton()
export class WebServer {
constructor(private _socketController: SocketController) { }
StartServer(): http.Server {
// http server instantiation logic
return httpServer;
}
SocketConnection(httpServer: http.Server): void {
const io = new Server(httpServer);
io.on('connection', (socket: Socket) => {
this._socketController.SocketMethods(socket, io);
});
}
}
SocketController
班级:
@singleton()
export class SocketController {
constructor(private _service: Service) { }
SocketMethods(socket: Socket, io: Server): void {
socket.on('method', async (params: any) => {
const res = await this._service.ServiceMethodAsync(params);
socket.emit('methodResponse', res);
}
});
}
}