c++ - 如何在运行时确定消息类型?

标签 c++ oop networking message packet

目前我正在为我的游戏服务器编写消息处理系统。我正在使用双分派(dispatch)设计模式根据从数据缓冲区检索到的消息 ID 选择所需的处理程序。但是我遇到了以下问题:我需要确定消息的派生类以将其传递给双分派(dispatch)处理程序对象。我找到的唯一解决方案是在基类中编写一个带有开关的工厂方法,它将根据消息 ID 创建所需的派生类。

class Message
{
public:
    void dispatch(Handler& handler)
    {
        dispatchImpl(handler);
    }

protected:
    virtual void dispatchImpl(Handler& handler) = 0;
};

template <typename TDerived>
class BaseMessage : public Message 
{
public:
    BaseMessage(unsigned short messageId)
        : id(messageId) {};

    virtual ~BaseMessage() = default;

    unsigned short getId() const { return id; }

    static std::unique_ptr<Message> create(BitStream& data)
    {
        switch (data.ReadShort())
        {
            case 1: return std::make_unique<FirstMessage>();
            case 2: return std::make_unique<SecondMessage>();
            case 3: return std::make_unique<ThirdMessage>();
            // ...
        }
    }

protected:
    unsigned short id;

    virtual void dispatchImpl(Handler& handler) override
    {
        handler.handle(static_cast<TDerived&>(*this));
    }
};

如何改进我的设计以避免大开关语句?提前致谢。

最佳答案

您可以使用 std::map<short,std::function<std::unique_ptr<Message> (BitStream& data)>并允许动态注册这些工厂函数:

std::map<short,std::function<std::unique_ptr<Message> (BitStream& data)> createMessageHandlers;

void registerCreateMessageHandler(short id,std::function<std::unique_ptr<Message> (BitStream& data)> fn) {
      createMessageHandlers[id] = fn;
}

像这样使用它

registerCreateMessageHandler(1, [](BitStream& data) { return std::make_unique<FirstMessage>();});
registerCreateMessageHandler(2, [](BitStream& data) { return std::make_unique<SecondMessage>();});

您的消息类型构造函数可能应该采用 BitStream&作为构造函数参数。


您应该考虑使用类似 google protocol buffers 的工具定义您的通信协议(protocol)。
这将有助于通过有线(或无线)进行正确的版本控制和解析消息包(字节序中性)。

结合例如boost::asiozeromq对于传输处理,这应该为您提供最大的灵 active 和适当的机制来分离通信的传输层和语义层。

关于c++ - 如何在运行时确定消息类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54079840/

相关文章:

c++ - 不确定有关 C++ Primer 中 Reference 的描述

java - 跟踪 Swing 组件的正确方法是什么?

wordpress - 如何从远程设备(例如 iPhone)测试本地开发的网站?

c++ - 使用模板将std::shared_ptr <Derived>上载到std::shared_ptr <Base>

c++ - CString 对象总是返回指针值

c# - (C#) 访问/修改列表中的对象

python - 如何创建 "list"类的子类,它在实例化时自行排序?

c# - 具有多个 IP 地址的网络接口(interface)上的 WCF Web 服务发现

c++ - 如何在qt中解析网络主机名+端口?

c++ - 关于 float