首页 > 代码库 > cocos2dx 消息发送与接收

cocos2dx 消息发送与接收

     cocos2dx有个自定义事件可以实现消息的发送和接收,叫EventListenerCustom。它是通过一个字符串来标识事件名称的。下面介绍下,我实现的这个消息的发送和接收。

     首先,我们定义2个类,一个消息接收类,一个消息发送类。代码如下:

     

//消息接收class cMsgReceiver{public:    virtual void RecMsg(int iMsgId, void* pInfo, int iSize)    {    }};//消息发送class cMsgSender{protected:    cMsgReceiver* m_pReceiver;public:    void setMsg(cMsgReceiver* receiver)    {        m_pReceiver = receiver;    }    bool sendMsg(int iMsgId, void* pInfo, int iSize)    {        if (m_pReceiver == NULL)        {            return false;        }        else        {            m_pReceiver->RecMsg(iMsgId, pInfo, iSize);            return true;        }    }};
View Code

 

        那么,如何使用呢,很简单。

 

//消息体struct Msg_ServerId{    int iServerId;};//消息idenum MsgId{   E_SERVERID = 1,};class A:public cMsgReceiver{public:    void RecMsg(int iMsgId, void* pInfo, int iSize)    {        switch (iMsgId)        {        case E_SERVERID:            Msg_ServerId* msg = (Msg_ServerId*)pInfo;            int id = msg->iServerId;            break;        }                }};class B:public cMsgSender{public:    void doSendMsg()    {        Msg_ServerId msg;        msg.iServerId = 1;        sendMsg(E_SERVERID, &msg, sizeof(msg));    }};
View Code

 

A a;B b;b.setMsg(&a);b.doSendMsg();

 

cocos2dx 消息发送与接收