1.1.2 • Published 1 year ago

@daisyengine/client.js v1.1.2

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

Daisy Engine JavaScript Client

JavaScript client to connect to Daisy Engine Servers.

Documentation

TBA.

Installation

NPM

npm install @daisyengine/client.js

YARN

yarn add @daisyengine/client.js

Usage

Here's a very simple chat example. We create a simple chat server and a client that connects to it and sends a message every second, while also printing out the chat history and new messages.

Server

import { Server, Room } from "@daisyengine/server";

class MyRoom extends Room {
  private _timer: NodeJS.Timeout;
  private _history: { name: string; message: string }[] = [];

  init() {
    this.onMessage("msg", (client, message) => {
      if (typeof message !== "string") return;

      this.addChatMessage(client.data, message);
    });

    this._timer = setInterval(() => this.processEvents(), 50);
  }

  addChatMessage(name, message) {
    this._history.push({ name, message });
    this._history = this._history.slice(-100);

    this.broadcast("new_msg", { name, message });
  }

  onClientJoined(client: NetworkClient) {
    client.data = "User " + client.id;
    client.send("history", this._history);

    this.addChatMessage("Server", client.data + " joined.");
  }

  onClientLeft(client: NetworkClient) {
    this.addChatMessage("Server", client.data + " left.");
  }

  cleanup() {
    clearInterval(this._timer);
  }
}

const myServer = new Server();

// Define a room
myServer.define("chat", MyRoom);

// Create a room
const roomInstance = myServer.createRoom("hello", "chat");

// Listen for new connections
myServer.listen(process.env.PORT || 3000);

Client

import { joinRoom } from "@daisyengine/client.js";

(async () => {
  const room = await joinRoom("ws://localhost:3000", "hello");

  var timer = setInterval(() => {
    room.send("msg", "Hello world! " + Date.now());
  }, 1000);

  room.onClose(() => {
    console.log("Connection closed.");
    clearInterval(timer);
  });
  room.onError((err) => {
    console.error(err);
    clearInterval(timer);
  });

  room.onMessage("new_msg", (data) => {
    console.log(data.name + ": " + data.message);
  });

  room.onMessage("history", (data) => {
    console.log("=== History ===");
    for (const msg of data) {
      console.log(msg.name + ": " + msg.message);
    }
  });
})();
1.1.2

1 year ago

1.1.1

1 year ago

1.1.0

1 year ago

1.0.1

1 year ago

1.0.0

1 year ago