服务器之消息处理
我这里的消息处理逻辑比较简单。
包括消息处理函数的声明宏: DEFINE_MESSAGE_CALLBACK_FUNC(msg)
消息处理函数定义宏: CALLBACK_FUNC_START(msg), CALLBACK_FUNC_END
消息注册函数的注册宏: REGISTER_MESSAGE_CALLBACK_FUNC(msg)
原本想将Class MessageDispatcher写成基类,但是涉及到模板参数,有些知识理解不足导致无法实现。
等之后实现了再放上基类版本!
头文件MessageDispatcher.h
#pragma once
#include <google/protobuf/descriptor.h>
#include <google/protobuf/message.h>
#include <map>
#include <functional>
// 前向申明,不需要include协议头文件
class MSG_1;
class MSG_2;
class MSG_3;
class MessageDispatcher;
typedef void(MessageDispatcher::*CallbackFunc)(int, google::protobuf::Message*);
typedef std::map<const google::protobuf::Descriptor*, CallbackFunc> CallbackMap;
// 定义消息处理函数
#define DEFINE_MESSAGE_CALLBACK_FUNC(msg) void OnSync##msg(int uniqueID, google::protobuf::Message* pMsg)
class MessageDispatcher
{
public:
MessageDispatcher();
~MessageDispatcher();
public:
static MessageDispatcher& GetIntance();
void Dispatch(int uniqueID, google::protobuf::Message* pMsg);
public:
DEFINE_MESSAGE_CALLBACK_FUNC(MSG_1);
DEFINE_MESSAGE_CALLBACK_FUNC(MSG_2);
DEFINE_MESSAGE_CALLBACK_FUNC(MSG_3);
public:
private:
CallbackMap m_callbackFuncs;
};
cpp文件MessageDispatch.cpp
#include "MessageDispatcher.h"
#include "..\Msg\MessageProto.pb.h"
// 注册消息处理函数
#define REGISTER_MESSAGE_CALLBACK_FUNC(msg)\
{\
auto descriptor = google::protobuf::DescriptorPool::generated_pool()->FindMessageTypeByName(#msg); \
if (descriptor != nullptr)\
{\
m_callbackFuncs[descriptor] = &MessageDispatcher::OnSync##msg; \
}\
}
// 消息处理函数的实现(开头)
#define CALLBACK_FUNC_START(msg)\
void MessageDispatcher::OnSync##msg(int uniqueID, google::protobuf::Message* pMsg)\
{\
msg* pDestMsg = (msg*)pMsg;\
// 消息处理函数的实现(结束)
#define CALLBACK_FUNC_END }
MessageDispatcher::MessageDispatcher()
{
REGISTER_MESSAGE_CALLBACK_FUNC(MSG_1);
REGISTER_MESSAGE_CALLBACK_FUNC(MSG_2);
REGISTER_MESSAGE_CALLBACK_FUNC(MSG_3);
}
MessageDispatcher::~MessageDispatcher()
{
}
MessageDispatcher& MessageDispatcher::GetIntance()
{
static MessageDispatcher one;
return one;
}
void MessageDispatcher::Dispatch(int uniqueID, google::protobuf::Message* pMsg)
{
if (nullptr == pMsg)
return;
const auto* descriptor = pMsg->GetDescriptor();
if (nullptr == descriptor)
return;
auto iter = m_callbackFuncs.find(descriptor);
if (iter == m_callbackFuncs.end())
return;
/*类成员函数指针在类中的调用方式*/
(this->*(iter->second))(uniqueID, pMsg);
}
void MessageFunc1(int uniqueID, MSG_1* pMsg)
{
}
void MessageFunc2(int uniqueID, MSG_2* pMsg)
{
}
void MessageFunc3(int uniqueID, MSG_3* pMsg)
{
}
CALLBACK_FUNC_START(MSG_1)
MessageFunc1(uniqueID, pDestMsg);
CALLBACK_FUNC_END
CALLBACK_FUNC_START(MSG_2)
MessageFunc2(uniqueID, pDestMsg);
CALLBACK_FUNC_END
CALLBACK_FUNC_START(MSG_3)
MessageFunc3(uniqueID, pDestMsg);
CALLBACK_FUNC_END
版权声明:本文为xp178171640原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。