cocos2d SocketIo列子

#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());
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值