cocos2dx websocket示例

来源:互联网 发布:发热丝数据 编辑:程序博客网 时间:2024/06/05 18:25

Cocos2dx封装了WebSocket,可以直接在项目中使用


[cpp] view plain copy
  1. //HelloWorldScene.h  
  2. #ifndef __HELLOWORLD_SCENE_H__  
  3. #define __HELLOWORLD_SCENE_H__  
  4.   
  5. #include "cocos2d.h"  
  6. #include "cocostudio/CocoStudio.h"  
  7. #include "ui/CocosGUI.h"  
  8. #include "network/WebSocket.h" //WebSocket头文件路径  
  9.   
  10. USING_NS_CC;  
  11. using namespace cocostudio::timeline;  
  12. using namespace cocos2d::network;//WebSocket名称空间  
  13. using namespace cocos2d::ui;  
  14.   
  15. class HelloWorld : public cocos2d::Layer, public WebSocket::Delegate //WebSocket委托  
  16. {  
  17. public:  
  18.     // there's no 'id' in cpp, so we recommend returning the class instance pointer  
  19.     static cocos2d::Scene* createScene();  
  20.     // Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning 'id' in cocos2d-iphone  
  21.     virtual bool init();  
  22.     // implement the "static create()" method manually  
  23.     CREATE_FUNC(HelloWorld);  
  24. private:  
  25.     //这些虚函数WebSocket的回调  
  26.     virtual void onOpen(WebSocket* ws);  
  27.     virtual void onMessage(WebSocket* ws, const WebSocket::Data& data);  
  28.     virtual void onClose(WebSocket* ws);  
  29.     virtual void onError(WebSocket* ws, const WebSocket::ErrorCode& error);  
  30. private:  
  31.     //WebSocket实例化  
  32.     WebSocket* m_pWebSocket;  
  33. };  
  34.   
  35. #endif // __HELLOWORLD_SCENE_H__  


[cpp] view plain copy
  1. //HelloWorldScene.h.cpp init函数  
  2. m_pWebSocket = new WebSocket();  
  3. m_pWebSocket->init(*this"ws://localhost:1234");//实例化WebSocket并连接  

[cpp] view plain copy
  1. /HelloWorldScene.h.cpp  
  2. void HelloWorld::onOpen(WebSocket * ws)  
  3. {  
  4.     CCLOG("OnOpen");  
  5. }  
  6.   
  7. void HelloWorld::onMessage(WebSocket * ws, const WebSocket::Data & data)  
  8. {  
  9.     std::string textStr = data.bytes;  
  10.     CCLOG(textStr.c_str());  
  11. }  
  12.   
  13. void HelloWorld::onClose(WebSocket * ws)  
  14. {  
  15.     if (ws == m_pWebSocket)  
  16.     {  
  17.         m_pWebSocket = NULL;  
  18.     }  
  19.     CC_SAFE_DELETE(ws);  
  20.     CCLOG("onClose");  
  21. }  
  22.   
  23. void HelloWorld::onError(WebSocket * ws, const WebSocket::ErrorCode & error)  
  24. {  
  25.     if (ws == m_pWebSocket)  
  26.     {  
  27.         char buf[100] = { 0 };  
  28.         sprintf(buf, "an error was fired, code: %d", error);  
  29.     }  
  30.     CCLOG("Error was fired, error code: %d", error);  
  31. }  



原创粉丝点击