如何使用Colyseus连接数据库, 这是新手程序员经常会问到的问题.
实际上, 只要有NodeJS支持的数据库驱动程序, 就可以使用Colyseus连接任意想要使用的数据库服务系统.
Colyseus在安装时会自动安装Redis数据库的驱动程序, 因为其内部使用Redis作为多实例的数据共享服务.
关于Colyseus与Redis的关系请参考这篇文章.
下面就以连接Redis数据库为例, 介绍如何连接数据库服务.

  • 客户端请求
    这里我们以Cocos Creator (Typescript) 为例, 发出连接数据库的请求.
import { _decorator, Component, Node } from 'cc';
const { ccclass, property } = _decorator;

import Colyseus from 'db://colyseus-sdk/colyseus.js';

@ccclass('NetworkManager')
export class NetworkManager extends Component {
    @property hostname = "localhost";
    @property port = 2567;
    @property useSSL = false;

    client!: Colyseus.Client;
    room!: Colyseus.Room;

    start () {
        // Instantiate Colyseus Client
        // connects into (ws|wss)://hostname[:port]
        this.client = new Colyseus.Client(this.useSSL ? "wss" : "ws" + "://" + this.hostname + (([443, 80].includes(this.port) || this.useSSL) ? "" : (":"+this.port)));

        // Connect into the room
        this.connect();
    }

    async connect() { 
        try {
            this.room = await this.client.joinOrCreate("my_room");

            console.log("joined successfully!");
            console.log("user's sessionId:", this.room.sessionId);

            // send a message request
            this.room.send("DB", "Hello, DB!");

            this.room.onStateChange((state) => {
                console.log("onStateChange: ", state);
            });

            this.room.onLeave((code) => {
                console.log("onLeave:", code);
            });

        } catch (e) {
            console.error(e);
        }
    }
}

请注意, 为了保证服务器的权威性, 客户端只能发送请求, 实际连接数据库的工作将在服务器端执行.

  • 服务器端Room
    Colyseus基于NodeJS, 所以确保在你的服务端已经正确安装NodeJS, Colyseus及数据库的驱动程序 (Colyseus自带Redis驱动程序).
import { Room, Client } from "colyseus";
import { MyRoomState } from "./schema/MyRoomState";

// import the Redis client
import { RedisClient } from "redis"

export class MyRoom extends Room<MyRoomState> {

  onCreate (options: any) {
    this.setState(new MyRoomState());

    // get the request from client
    this.onMessage("DB", (client, message) => {

      // connect to Redis database
      let rc = new RedisClient({host:"localhost", port:6379});

      // add the message to database
      rc.set("somebody", message);

      // save it
      rc.save();

      // find the message from client in Redis
      rc.get("somebody", (err, value)=>{console.log(value)});
    });

  }

  onJoin (client: Client, options: any) {
    console.log(client.sessionId, "joined!");
  }

  onLeave (client: Client, consented: boolean) {
    console.log(client.sessionId, "left!");
  }

  onDispose() {
    console.log("room", this.roomId, "disposing...");
  }

}

很简单是不是, 注意这里忽略了商业应用必要的错误检查之类的代码.

  • 测试
    首先启动服务器, 然后再启动客户端.
    顺利的话你会在服务器控制台上看到来自客户端的问候.
    0_1629876058353_f35521ac-6d2f-415c-b4ae-bdf168cabed4-image.png