加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Cocos2dx WebSocket的使用

发布时间:2020-12-14 17:20:43 所属栏目:百科 来源:网络整理
导读:转自: http://blog.csdn.net/a19352226/article/details/50850845 Cocos2dx封装了WebSocket,可以直接在项目中使用 废话不多说,直接上代码 [cpp] view plain copy //HelloWorldScene.h #ifndef__HELLOWORLD_SCENE_H__ #define__HELLOWORLD_SCENE_H__ #include

转自: http://blog.csdn.net/a19352226/article/details/50850845


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


废话不多说,直接上代码

[cpp] view plain copy
  1. //HelloWorldScene.h
  2. #ifndef__HELLOWORLD_SCENE_H__
  3. #define__HELLOWORLD_SCENE_H__
  4. #include"cocos2d.h"
  5. #include"cocostudio/CocoStudio.h"
  6. #include"ui/CocosGUI.h"
  7. #include"network/WebSocket.h"//WebSocket头文件路径
  8. USING_NS_CC;
  9. usingnamespacecocostudio::timeline;
  10. namespacecocos2d::network;//WebSocket名称空间
  11. namespacecocos2d::ui;
  12. classHelloWorld:publiccocos2d::Layer,publicWebSocket::Delegate//WebSocket委托
  13. {
  14. public:
  15. //there'sno'id'incpp,sowerecommendreturningtheclassinstancepointer
  16. staticcocos2d::Scene*createScene();
  17. //Here'sadifference.Method'init'incocos2d-xreturnsbool,insteadofreturning'id'incocos2d-iphone
  18. virtualboolinit();
  19. //implementthe"staticcreate()"methodmanually
  20. CREATE_FUNC(HelloWorld);
  21. private:
  22. //这些虚函数WebSocket的回调
  23. virtualvoidonOpen(WebSocket*ws);
  24. voidonMessage(WebSocket*ws,153); background-color:inherit; font-weight:bold">constWebSocket::Data&data);
  25. voidonClose(WebSocket*ws);
  26. voidonError(WebSocket*ws,153); background-color:inherit; font-weight:bold">constWebSocket::ErrorCode&error);
  27. //WebSocket实例化
  28. WebSocket*m_pWebSocket;
  29. };
  30. #endif//__HELLOWORLD_SCENE_H__


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

  • copy
    /HelloWorldScene.h.cpp
  • voidHelloWorld::onOpen(WebSocket*ws)
  • {
  • CCLOG("OnOpen");
  • }
  • voidHelloWorld::onMessage(WebSocket*ws,153); background-color:inherit; font-weight:bold">constWebSocket::Data&data)
  • std::stringtextStr=data.bytes;
  • CCLOG(textStr.c_str());
  • voidHelloWorld::onClose(WebSocket*ws)
  • if(ws==m_pWebSocket)
  • m_pWebSocket=NULL;
  • }
  • CC_SAFE_DELETE(ws);
  • CCLOG("onClose");
  • voidHelloWorld::onError(WebSocket*ws,153); background-color:inherit; font-weight:bold">constWebSocket::ErrorCode&error)
  • charbuf[100]={0};
  • sprintf(buf,"anerrorwasfired,code:%d",error);
  • CCLOG("Errorwasfired,errorcode:%d",108); list-style-type:decimal-leading-zero; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important; list-style-position:outside!important"> }

  • 就这么简单!

    (编辑:李大同)

    【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

      推荐文章
        热点阅读