#pragma once
#include "cocos2d.h"
#include "network/SocketIO.h"
using namespace cocos2d;
using namespace cocos2d::network;
class textSocketIo :public Layer,SocketIO::SIODelegate
{
public:
static Scene*createScene();
CREATE_FUNC(textSocketIo);
bool init();
virtual void onConnect(SIOClient* client);
virtual void onMessage(SIOClient* client, const std::string& data);
virtual void onClose(SIOClient* client);
virtual void onError(SIOClient* client, const std::string& data);
void sendEvent();
void closeSocket();
SIOClient *_socklient;
};
#include "textSocketIo.h"
Scene* textSocketIo::createScene()
{
Scene*s = Scene::create();
textSocketIo *l = textSocketIo::create();
s->addChild(l);
return s;
}
bool textSocketIo::init()
{
if (!Layer::init())return false;
_socklient = nullptr;
auto menu = Menu::create();
this->addChild(menu);
auto lblInit = Label::create("Init socket", "Arial", 22);
auto menuInit = MenuItemLabel::create(lblInit, [=](Ref*)
{
if (!_socklient)
{
_socklient = SocketIO::connect("127.0.0.1:6000",*this);
if (_socklient)
{
_socklient->setTag("init socket");
_socklient->on("textevent", [=](SIOClient* c, const std::string& data)
{
log("textSocked::textevent called with data %s",data.c_str());
});
_socklient->on("event", [=](SIOClient* c, const std::string& data)
{
log("textSocked::event called with data %s",data.c_str());
});
}
}
});
auto lblSend = Label::create("send message","Arial",22);
auto menuSend = MenuItemLabel::create(lblSend, [=](Ref*)
{
if (_socklient)
{
_socklient->send("hello socket Io");
}
});
menu->addChild(menuInit);
menu->addChild(menuSend);
menu->alignItemsVertically();
return true;
}
void textSocketIo::sendEvent()
{
if (_socklient)
_socklient->emit("event", "[{\"name\":\"myname\",\"type\":\"mytype\"}]");
}
void textSocketIo::closeSocket()
{
if (_socklient)
_socklient->disconnect();
}
void textSocketIo::onConnect(SIOClient* client)
{
log("onConnect ");
log("%s connect",client->getTag());
}
void textSocketIo::onMessage(SIOClient* client, const std::string& data)
{
log("onMessage");
log("%s received content is :%s",client->getTag(),data.c_str());
}
void textSocketIo::onClose(SIOClient* client)
{
log("onClose");
log("%s is close",client->getTag());
}
void textSocketIo::onError(SIOClient* client, const std::string& data)
{
log("onError");
log("%s is Error %s",client->getTag(),data.c_str());
}