我正在创建用于匹配的nodejs应用: 当我将套接字实例传递给匹配类时,如果其中一个客户端断开连接并且匹配类中的套接字侦听器再也无法工作,则连接会死掉
server.ts
class SocketServer {
public server: Server;
public matches: Match[] = [];
private io: socketIo.Server;
constructor() {
this.createServer();
this.sockets();
this.listen();
}
private createServer(): void {
this.server = createServer();
}
private sockets(): void {
this.io = socketIo(this.server);
}
private listen(): void {
this.server.listen(this.port, this.host, () => {
console.log("http://%s:%s", this.host, this.port);
});
const nsp = this.io.of("my-namespace")
.on("connection", (socket: any) => {
const query = {
client_id: Number(socket.handshake.query.client_id),
match: Number(socket.handshake.query.match) };
socket.join(query.match.toString());
socket.on("subscribe", (room: string) => {
socket.join(room);
});
socket.on("unsubscribe", (room: string) => {
socket.leave(room);
});
if (this.matches.length > 0) {
const match = this.findMatchById(query.match);
if (match === undefined) {
this.matches.push(new Match(nsp, socket, query));
}
} else {
this.matches.push(new Match(nsp, socket, query));
}
});
}
}
在比赛类中,当我使用io.emit()
时,它可以正常工作,但是socket.on()
在任何客户端从比赛中断开连接后,它都无法工作
match.ts
export default class Match {
constructor(namespace: any, socket: any, query: any) {
this.namespace = namespace;
this.room = query.match.toString();
this.id = query.match;
this.main(socket, query);
}
public async main(socket: any, query: any) {
if (this.initiated === false) {
await this.initMatch();
}
socket.on("player-ready", (data: any) => {
// some code
});
socket.on("disconnect", () => {
// some code
});
}
}
答案 0 :(得分:0)
我发现问题出在哪里,当我将套接字实例传递给Match构造函数时,由于条件的限制,我让一个客户端连接到了房间
if (this.matches.length > 0) {
const match = this.findMatchById(query.match);
if (match === undefined) {
this.matches.push(new Match(nsp, socket, query));
}
} else {
this.matches.push(new Match(nsp, socket, query));
}
我从不让其他人在同一场比赛中注册,因此我在match类中创建了一些公共方法,并在服务器文件中使用了这样的方法:
match.ts
public makeClientReady(id: number): void {
// some code
}
server.ts
const nsp = this.io.of("my-namespace")
.on("connection", (socket: any) => {
const query = {
client_id: Number(socket.handshake.query.client_id),
match: Number(socket.handshake.query.match) };
socket.join(query.match.toString());
socket.on("subscribe", (room: string) => {
socket.join(room);
});
socket.on("unsubscribe", (room: string) => {
socket.leave(room);
});
if (this.matches.length > 0) {
const match = this.findMatchById(query.match);
if (match === undefined) {
this.matches.push(new Match(nsp, socket, query));
}
} else {
this.matches.push(new Match(nsp, socket, query));
}
socket.on("player-ready", (data: any) => {
match.makeClientReady(Number(data.id));
});
});