Cocos2dx WebSocket的使用

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

就这么简单!


  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值