better websocket error/close handling

This commit is contained in:
vel 2022-01-26 23:45:39 -08:00
parent cad2d85ce4
commit e8e5b7e409
Signed by: velvox
GPG Key ID: 1C8200C1D689CEF5
1 changed files with 28 additions and 2 deletions

View File

@ -1,6 +1,7 @@
// nice and easy way to get types for the // nice and easy way to get types for the
import { User } from "next-auth"; import { User } from "next-auth";
import EventEmitter from "events";
import IdentityData from "../interfaces/Identity"; import IdentityData from "../interfaces/Identity";
import { MessageTypes } from "../interfaces/IMessage"; import { MessageTypes } from "../interfaces/IMessage";
import Message from "../util/Message"; import Message from "../util/Message";
@ -15,15 +16,28 @@ if (typeof window !== "undefined") {
} }
export default class PlayerSocket extends Websocket { export default class PlayerSocket extends Websocket {
private clientID: string;
public emitter: EventEmitter;
constructor(private user: User) { constructor(private user: User) {
super(process.env.NEXT_PUBLIC_WS_URI); super(process.env.NEXT_PUBLIC_WS_URI);
this.emitter = new EventEmitter();
this.clientID = process.env.NEXT_PUBLIC_CLIENT_ID;
this.onopen = this.onOpen; this.onopen = this.onOpen;
this.onmessage = this.onMessage;
this.onclose = this.onClose;
}
onMessage(evt: MessageEvent<any>) {
let message = MessageUtil.decode(evt.data);
if (message.type === MessageTypes["Ping"]) {
return;
}
this.emitter.emit(MessageTypes[message.type], message.data);
} }
onOpen() { onOpen() {
this.send( this.send(
MessageUtil.encode( MessageUtil.encode(
new Message(MessageTypes.Identify, { new Message(MessageTypes.Identify, {
clientID: process.env.NEXT_PUBLIC_CLIENT_ID, clientID: this.clientID,
user: { user: {
id: this.user.id, id: this.user.id,
name: this.user.name, name: this.user.name,
@ -31,6 +45,7 @@ export default class PlayerSocket extends Websocket {
} as IdentityData) } as IdentityData)
) )
); );
this.emitter.emit("open");
this.pingEvent(); this.pingEvent();
} }
pingEvent() { pingEvent() {
@ -40,9 +55,20 @@ export default class PlayerSocket extends Websocket {
return; return;
} }
console.log("[WS] running ping event"); console.log("[WS] running ping event");
this.send(MessageUtil.encode(new Message(MessageTypes.Ping))); this.send(
MessageUtil.encode(
new Message(MessageTypes.Ping, {
clientID: this.clientID,
})
)
);
}, 20000); }, 20000);
} }
onClose(event: CloseEvent) {
console.log("[WS] socket connection closed");
console.log(event);
this.emitter.emit("closed");
}
get open() { get open() {
return this.readyState === this.OPEN; return this.readyState === this.OPEN;
} }