Cocos2d-x3.8.1网络编程(Socket)

来源:互联网 发布:微盟weimob源码下载 编辑:程序博客网 时间:2024/05/14 07:03

//同样的Cocos2d-x游戏引擎为socket进行了封装整合

//加入头文件

#include "network/SocketIO.h"


//加入命名空间

using namespace cocos2d::network;


//.h文件

//继承SocketIO内部类中的SIODelegate类

class HelloWorld : public cocos2d::Layer,cocos2d::network::SocketIO::SIODelegate
{
public:
    static cocos2d::Scene* createScene();

    virtual bool init();
    
    // implement the "static create()" method manually
    CREATE_FUNC(HelloWorld);


//重写SIODelegate类中的四个虚函数


virtual void onConnect(cocos2d::network::SIOClient* client);


virtual void onMessage(cocos2d::network::SIOClient* client,const std::string& data);


virtual void onClose(cocos2d::network::SIOClient* client);


virtual void onError(cocos2d::network::SIOClient* client,const std::string& data);


cocos2d::network::SIOClient* client;

};




//.cpp文件


bool HelloWorld::init()
{
    //////////////////////////////
    // 1. super init first
    if (!Layer::init())
    {
        return false;
    }


Size size = Director::getInstance()->getWinSize();

//初始化,置为NULL
client=nullptr;

//为了方便检测设置Label文本

auto menu=Menu::create();
menu->setPosition(Vec2::ZERO);
this->addChild(menu);


auto openSocketLabel=Label::create("openSocket","Arial",24.0f);
auto openSocketItem=MenuItemLabel::create(openSocketLabel,[this](Ref* ref)
{
//创建客户端对象并连接服务器
client=SocketIO::connect("ws://192.168.1.103:3000", *this);
client->setTag("HelloWord");

//自定义事件侦听,接收信号,与client->emit()相对应
client->on("log",[this](SIOClient* m_client,const std::string& data)
{
log("emit message:&s",data.c_str());
});
});
openSocketItem->setPosition(size/2);
menu->addChild(openSocketItem);






auto sendSocketLabel=Label::create("sendSocket","Arial",24.0f);
auto sendSocketItem=MenuItemLabel::create(sendSocketLabel,[this](Ref* ref)
{

//发送数据
client->send("LiuJunLiang");
});
sendSocketItem->setPosition(Vec2(size.width/2,size.height/2-50));
menu->addChild(sendSocketItem);




auto emitSocketLabel=Label::create("emitSocket","Arial",24.0f);
auto emitSocketItem=MenuItemLabel::create(emitSocketLabel,[this](Ref*)
{

//自定义侦听事件,发射信号
client->emit("log","helloCocos");
});
emitSocketItem->setPosition(size.width/2,size.height/2-100);
menu->addChild(emitSocketItem);


    
    return true;
}



void HelloWorld::onConnect(cocos2d::network::SIOClient* client)
{
log("%s is opening",client->getTag());
}


void HelloWorld::onMessage(cocos2d::network::SIOClient* client,const std::string& data)
{
log("%s send message:%s",client->getTag(),data.c_str());
}


void HelloWorld::onClose(cocos2d::network::SIOClient* client)
{
log("%s is closing",client->getTag());
}


void HelloWorld::onError(cocos2d::network::SIOClient* client,const std::string& data)
{
log("%s make error:%s",client->getTag(),data.c_str());
}

0 0
原创粉丝点击