Up to date

This page is up to date for Godot 4.2. If you still find outdated information, please open an issue.

自定义 Godot 服务器

前言

Godot将多线程实现为服务器. 服务器是管理数据, 处理数据和推送结果的守护进程. 服务器实现中介模式, 该模式解释引擎和其他模块的资源ID和处理数据. 此外, 服务器声明其RID分配的所有权.

This guide assumes the reader knows how to create C++ modules and Godot data types. If not, refer to 自定义 C++ 模块.

参考

可以做什么?

  • 添加人工智能.

  • 添加自定义异步线程.

  • 添加对新输入设备的支持.

  • 添加写线程.

  • 添加自定义 VoIP 协议。

  • 以及更多……

创建 Godot 服务器

服务器至少必须拥有静态的实例、睡眠计时器、线程循环、初始化状态、清理过程。

#ifndef HILBERT_HOTEL_H
#define HILBERT_HOTEL_H

#include "core/object/object.h"
#include "core/os/thread.h"
#include "core/os/mutex.h"
#include "core/templates/list.h"
#include "core/templates/rid.h"
#include "core/templates/set.h"
#include "core/variant/variant.h"

class HilbertHotel : public Object {
        GDCLASS(HilbertHotel, Object);

        static HilbertHotel *singleton;
        static void thread_func(void *p_udata);

private:
        bool thread_exited;
        mutable bool exit_thread;
        Thread *thread;
        Mutex *mutex;

public