NetClient.js 1.65 KB
Newer Older
Alexander Bazo committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
/* eslint-env browser */
/* global Colyseus */

import Logger from "../utils/Logger.js";
import Observable from "../utils/Observable.js";

const DEFAULT_GAME_ROOM = "image_viewer";

class NetClient extends Observable {

  constructor(url) {
    super();
    this.url = url;
  }

  connect(asObserver) {
    this.isObserver = asObserver;
    this.client = new Colyseus.Client(this.url);
    this.client.joinOrCreate(DEFAULT_GAME_ROOM).then(this.onConnect.bind(this))
      .catch(this.onError.bind(this));
  }

  sendGazeData(gazeData) {
    if (this.room === undefined) {
      return;
    }
    this.room.send({
      type: "gaze",
      data: gazeData,
    });
  }

  onConnect(room) {
    Logger.log(`Viewer ${room.sessionId} joined ${room.name}`, "NetClient");
    this.room = room;
    this.room.onStateChange(this.onUpdate.bind(this));
    this.room.onMessage(this.onMessage.bind(this));
    this.room.onError(this.onError.bind(this));
    this.room.onLeave(this.onLeave.bind(this));
    if (this.isObserver === true) {
      this.room.send({
        type: "subscribeToGazeData",
      });
    }
    this.notifyAll({
      type: "connect",
      ownID: this.room.sessionId,
    });

  }

  onUpdate(state) {
    this.notifyAll({
      type: "stateupdate",
      state: state,
    });
  }

  onMessage(message) {
    Logger.log("Received new message from server", "NetClient");
    if (message.type === "gazelist") {
      this.notifyAll({
        type: "gazeupdate",
        gazepoints: message.data,
      });
    }
  }

  onError(error) {
    Logger.log(error, "NetClient");
  }

  onLeave() {
    Logger.log("Local client left room", "NetClient");
  }
}

export default NetClient;