Cocos2dx WebSocket的使用
发布时间:2020-12-14 16:56:38 所属栏目:百科 来源:网络整理
导读:Cocos2dx封装了WebSocket,可以直接在项目中使用 废话不多说,直接上代码 //HelloWorldScene.h#ifndef __HELLOWORLD_SCENE_H__#define __HELLOWORLD_SCENE_H__#include "cocos2d.h"#include "cocostudio/CocoStudio.h"#include "ui/CocosGUI.h"#include "netwo
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); }就这么简单! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |