Implementing a Message Handler

Started by
9 comments, last by Zern 21 years, 2 months ago
I''d go for the plugable factories method too. YOu could do something like this:

  // Client & Server Header   struct WorldState{   vector<Client> vClients;   // Other world info here};   class IMessageHandler{public:   virtual void Release() = 0;   virtual bool HandleMessage(int nMsg, void* pMsgData) = 0;};  IMessageHandler* Create(WorldState* pState);typedef IMessageHandler* (*pfnCreate)(WorldState* pState);  


  // DLL Headerclass CMessageHandler : public IMessageHandler{public:   CMessageHandler(WorldState* pState) :m_pState(pState) {}    virtual void Release() {delete this;}   virtual bool HandleMessage(int nMsg, void* pMsgData);  protected:   WorldState* m_pState;   // Usual member variables etc here};   // DLL SourceIMessageHandler* Create(WorldState* pState){   return new CMessageHandler(pState);}   bool CMessageHandler::HandleMessage(int nMsg, void* pMsgData){User* pUser;      switch(nMsg)   {   case 1000:      pUser = (SUser*)pMsgData;      m_pState->listOfUsers.Remove(pUser->ID);      return true;      default:      return false;   }}  



  // In the servers init code (server has variable m_pHandler)// IMessageHandler* m_pHandler;  HMODULE hMod = LoadLibrary("Messages.dll");pfnCreate func = (pfnCreate)GetProcAddress("Create");m_pHandler = func(m_pState);  // When server recieves a message:m_pHandler->HandleHessage(int nMsg, void* pData);  


I haven''t tested that code at all, its just as an example. So you pass the message handler a state block, which should have information about all the users in it along with other information. If you use e.g. a vector, you''ll have to be careful not to allocate memory in the DLL and free it in the EXE (or vice-versa).
When you recieve a message, you pass it along to your message handler in your DLL. Maybe abstract classes is overkill, you could just as well go and have a function, and a global for the world state.

HTH

Member of the Unban Mindwipe Society (UMWS)

This topic is closed to new replies.

Advertisement