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.cppvoID 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);}就这么简单! 总结
以上是内存溢出为你收集整理的Cocos2dx WebSocket的使用全部内容,希望文章能够帮你解决Cocos2dx WebSocket的使用所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)