您的位置:首页 > 移动开发 > Cocos引擎

Cocos2dx WebSocket的使用

2016-03-10 23:00 351 查看
Cocos2dx封装了WebSocket,可以直接在项目中使用

废话不多说,直接上代码

//HelloWorldScene.h
#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__

#include "cocos2d.h"
#include "cocostudio/CocoStudio.h"
#include "ui/CocosGUI.h"
#include "network/WebSocket.h" //WebSocket头文件路径

USING_NS_CC;
using namespace cocostudio::timeline;
using namespace cocos2d::network;//WebSocket名称空间
using namespace cocos2d::ui;

class HelloWorld : public cocos2d::Layer, public WebSocket::Delegate //WebSocket委托
{
public:
// there's no 'id' in cpp, so we recommend returning the class instance pointer
static cocos2d::Scene* createScene();
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone
virtual bool init();
// implement the "static create()" method manually
CREATE_FUNC(HelloWorld);
private:
//这些虚函数WebSocket的回调
virtual void onOpen(WebSocket* ws);
virtual void onMessage(WebSocket* ws, const WebSocket::Data& data);
virtual void onClose(WebSocket* ws);
virtual void onError(WebSocket* ws, const WebSocket::ErrorCode& error);
private:
//WebSocket实例化
WebSocket* m_pWebSocket;
};

#endif // __HELLOWORLD_SCENE_H__


//HelloWorldScene.h.cpp init函数
m_pWebSocket = new WebSocket();
m_pWebSocket->init(*this, "ws://localhost:1234");//实例化WebSocket并连接


/HelloWorldScene.h.cpp
void HelloWorld::onOpen(WebSocket * ws)
{
CCLOG("OnOpen");
}

void HelloWorld::onMessage(WebSocket * ws, const WebSocket::Data & data)
{
std::string textStr = data.bytes;
CCLOG(textStr.c_str());
}

void HelloWorld::onClose(WebSocket * ws)
{
if (ws == m_pWebSocket)
{
m_pWebSocket = NULL;
}
CC_SAFE_DELETE(ws);
CCLOG("onClose");
}

void HelloWorld::onError(WebSocket * ws, const WebSocket::ErrorCode & error)
{
if (ws == m_pWebSocket)
{
char buf[100] = { 0 };
sprintf(buf, "an error was fired, code: %d", error);
}
CCLOG("Error was fired, error code: %d", error);
}


就这么简单!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: