1.MsgDispatcher.h
/********************************************************************
File name: MsgDispatcher.h
Author: lieyingshengbao
Version: 1.0
Date: 2012-09-28
Description: 本文件是核心,为消息分发器
Others: 本类型使用C++定义
Function List: 请参见正文
History: 修改历史记录列表,每条修改记录应包括修改日期、修改者及修改内容简述
1. Date:
Author:
Modification:
2. ...
*********************************************************************/
#ifndef _MSGDISPATCHER_H_
#define _MSGDISPATCHER_H_
#include "MsgProcer.h"
#include <map>
using std::map;
class MsgDispatcher
{
public:
MsgDispatcher(CAPMsgQueue* pMsgQueue);
virtual ~MsgDispatcher(){};
public:
void RegisteProcesser(MsgProcer* pProcesser); //将处理器注册到分发器中
u_int GetMsgCommandId(CMsg* pMsg);
int Run();
private:
static unsigned __stdcall MsgLoop(LPVOID Param);
private:
map<u_int, MsgProcer*> m_mapProcesser;
CAPMsgQueue* m_pMsgQueue;
};
#endif
MsgDispatcher.cpp
#include "stdafx.h"
#include "MsgDispatcher.h"
//获取消息队列
MsgDispatcher::MsgDispatcher(CAPMsgQueue* pMsgQueue)
{
m_pMsgQueue = pMsgQueue;
}
//注册派生类的处理器。将消息的CommandId和处理器对应
void MsgDispatcher::RegisteProcesser(MsgProcer* pProcesser)
{
vector<u_int> veCmds;
pProcesser->GetCommandId(veCmds); //多态会调用子类的方法,获取CommandId
vector<u_int>::iterator itCmds;
for (itCmds=veCmds.begin(); itCmds!=veCmds.end(); ++itCmds)
{
m_mapProcesser.insert(map<u_int, MsgProcer*>::value_type(*itCmds, pProcesser));
}
return;
}
//取出消息的CommandId
u_int MsgDispatcher::GetMsgCommandId(CMsg* pMsg)
{
CommonHead_S* pCommon = (CommonHead_S*)pMsg->cArry;
u_int uCommandId = pCommon->uMsgCommandId;
return uCommandId;
}
unsigned __stdcall MsgDispatcher::MsgLoop(LPVOID lpParameter)
{
MsgDispatcher* pThis = (MsgDispatcher*)lpParameter;
while (true)
{
CMsg* pMsg = pThis->m_pMsgQueue->GetMsg();
if ( NULL != pMsg )
{
u_int uCommandId = pThis->GetMsgCommandId(pMsg);
map<u_int, MsgProcer*>::iterator itCmds;
for (itCmds=pThis->m_mapProcesser.begin(); itCmds!=pThis->m_mapProcesser.end(); ++itCmds)
{
if (uCommandId == itCmds->first)
{
itCmds->second->OnMessage(pMsg);
break;
}
}
}
}
return 0;
}
int MsgDispatcher::Run()
{
HANDLE ThreadHandle = (HANDLE)_beginthreadex(NULL,
0,
MsgDispatcher::MsgLoop,
(LPVOID)(this),
0,
NULL);
if (NULL == ThreadHandle)
{
return 1;
}
return 0;
}