保持客户端 - 服务器游戏中的代码组织

faf*_*ffy 10 c++ architecture oop design-patterns code-separation

背景: 我帮助开发一种多人游戏,主要用C++编写,使用标准的客户端 - 服务器架构.服务器可以自己编译,客户端与服务器一起编译,因此您可以托管游戏.

问题

游戏将客户端和服务器代码组合到同一个类中,这开始变得非常麻烦.

例如,以下是您在公共类中可能看到的一些小样本:

// Server + client
Point Ship::calcPosition()
{
  // Do position calculations; actual (server) and predictive (client)
}

// Server only
void Ship::explode()
{
  // Communicate to the client that this ship has died
}

// Client only
#ifndef SERVER_ONLY
void Ship::renderExplosion()
{
  // Renders explosion graphics and sound effects
}
#endif
Run Code Online (Sandbox Code Playgroud)

标题:

class Ship
{
    // Server + client
    Point calcPosition();

    // Server only
    void explode();

    // Client only
    #ifndef SERVER_ONLY
    void renderExplosion();
    #endif
}
Run Code Online (Sandbox Code Playgroud)

如您所见,仅在编译服务器时,预处理器定义用于排除图形和声音代码(这看起来很丑陋).

题:

保持客户端 - 服务器体系结构中的代码有条理和清洁的一些最佳实践是什么?

谢谢!

编辑:欢迎使用良好组织的开源项目示例:)

byt*_*ter 2

定义具有客户端 API 的客户端存根类。

定义实现服务器的服务器类。

定义一个服务器存根,将传入消息映射到服务器调用。

存根类除了通过您使用的协议将命令代理到服务器之外没有任何实现。

您现在可以在不改变设计的情况下更改协议。

或者

使用MACE-RPC等库从服务器 API 自动生成客户端和服务器存根。