From 61f8345d75c3f69252feba26b5eab25be4e16174 Mon Sep 17 00:00:00 2001 From: Endel Dreyer Date: Sun, 4 Jun 2017 01:12:41 +0200 Subject: [PATCH] disconnect websocket instead of sending LEAVE_ROOM. --- src/Client.ts | 17 +++++++---------- src/Room.ts | 22 +++++++++++----------- 2 files changed, 18 insertions(+), 21 deletions(-) diff --git a/src/Client.ts b/src/Client.ts index 005ad22..ce37bb9 100644 --- a/src/Client.ts +++ b/src/Client.ts @@ -19,18 +19,15 @@ export class Client { onError: Signal = new Signal(); constructor (url: string) { + let colyseusid = cookie.getItem('colyseusid'); + if (colyseusid) { + this.id = colyseusid; + } + this.connection = new Connection(url); this.connection.onmessage = this.onMessageCallback.bind(this); - this.connection.onclose = this.onCloseCallback.bind(this); - this.connection.onerror = this.onErrorCallback.bind(this); - } - - onCloseCallback () { - this.onClose.dispatch(); - } - - onErrorCallback () { - this.onError.dispatch(); + this.connection.onclose = (e) => this.onClose.dispatch(); + this.connection.onerror = (e) => this.onError.dispatch(); } join (roomName: string, options: any = {}): Room { diff --git a/src/Room.ts b/src/Room.ts index 140837b..84a79a0 100644 --- a/src/Room.ts +++ b/src/Room.ts @@ -40,11 +40,8 @@ export class Room { connect (connection: Connection) { this.connection = connection; this.connection.onmessage = this.onMessageCallback.bind(this); - this.connection.onopen = this.onOpenCallback.bind(this); - } - - protected onOpenCallback (event) { - this.onJoin.dispatch(); + this.connection.onopen = (e) => this.onJoin.dispatch(); + this.connection.onclose = (e) => this.onLeave.dispatch(); } protected onMessageCallback (event) { @@ -54,9 +51,6 @@ export class Room { if (code == Protocol.JOIN_ERROR) { this.onError.dispatch(message[2]); - } else if (code == Protocol.LEAVE_ROOM) { - this.onLeave.dispatch(); - } else if (code == Protocol.ROOM_STATE) { let state = message[2]; let remoteCurrentTime = message[3]; @@ -69,10 +63,12 @@ export class Room { } else if (code == Protocol.ROOM_DATA) { this.onData.dispatch(message[2]); + + } else if (code == Protocol.LEAVE_ROOM) { + this.leave(); } } - setState ( state: T, remoteCurrentTime?: number, remoteElapsedTime?: number ): void { this.state.set(state); this._previousState = msgpack.encode( state ) @@ -112,14 +108,18 @@ export class Room { } public leave (): void { - if (this.id >= 0) { + if (this.id) { this.connection.close(); // this.connection.send([ Protocol.LEAVE_ROOM, this.id ]); } } public send (data): void { - this.connection.send([ Protocol.ROOM_DATA, this.id, data ]); + if (this.connection.readyState === WebSocket.OPEN) { + this.connection.send([ Protocol.ROOM_DATA, this.id, data ]); + } else { + console.warn("Room", this.id, "is not connected."); + } } public removeAllListeners = (): void => {