赞
踩
- #pragma once
- #include "cocos2d.h"
- #include "network/WebSocket.h"
-
- using namespace cocos2d;
- using namespace cocos2d::network;
-
- class TestWebSocketScene: public Layer ,WebSocket::Delegate
- {
- public:
- CREATE_FUNC(TestWebSocketScene);
- static Scene *createScene();
- bool init();
-
-
- 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 *wsText;
- };
- #include "TestWebSocketScene.h"
-
-
- Scene *TestWebSocketScene::createScene()
- {
- Scene *s = Scene::create();
- auto l = TestWebSocketScene::create();
- s->addChild(l);
- return s;
- }
- bool TestWebSocketScene::init()
- {
- if (!Layer::init())return false;
-
- Size size = Director::getInstance()->getWinSize();
-
-
- wsText = nullptr;
-
-
-
- auto menu = Menu::create();
-
-
-
- this->addChild(menu);
-
- auto lblSendText = Label::create("init websocket text","Arial",22);
-
-
- auto menuSendText = MenuItemLabel::create(lblSendText, [=](Ref*sender)
- {
- wsText = new WebSocket();
- if (!wsText->init(*this, "ws://echo.websocket.org"))
- {
- CC_SAFE_DELETE(wsText);
- }
-
- });
-
- auto lalSend = Label::create("send text","Arial",22);
-
- auto menuSend = MenuItemLabel::create(lalSend, [=](Ref*)
- {
- if (wsText)
- {
- wsText->send("hello websocket");
- }
- });
-
- auto lalSendBinary = Label::create("send Binary", "Arial", 22);
-
- auto menuSendBinary = MenuItemLabel::create(lalSendBinary, [=](Ref*)
- {
- if (wsText)
- {
- char buffer[] = "hello \0 binary";
- wsText->send((unsigned char*)buffer,sizeof(buffer));
- }
- });
-
- menu->addChild(menuSendText);
- menu->addChild(menuSend);
- menu->addChild(menuSendBinary);
-
-
- menu->alignItemsVertically();
-
-
-
-
-
-
-
-
- return true;
- }
-
-
- void TestWebSocketScene::onOpen(WebSocket* ws)
- {
- log("WebSocket (%p) open",ws);
- if (ws&&wsText == ws)
- {
- log("WebSocket send text open");
- }
- }
-
- void TestWebSocketScene::onMessage(WebSocket* ws, const WebSocket::Data& data)
- {
- log("WebSocket (%p) onMessage", ws);
- if (!data.isBinary)
- {
- log("received %s",data.bytes);
- }
- else
- {
- std::string result;
- for (int i = 0; i < data.len; i++)
- {
- if (data.bytes[i] != '\0')
- {
- result += data.bytes[i];
- }
- else
- {
- result += "\'\\0'";
- }
- }
- log("recceived binary is :%s",result.c_str());
- }
- }
-
- void TestWebSocketScene::onClose(WebSocket* ws)
- {
- log("WebSocket (%p) onClose", ws);
- if (ws&&wsText == ws)
- {
- log("WebSocket send text onClose");
- }
- }
-
- void TestWebSocketScene::onError(WebSocket* ws, const WebSocket::ErrorCode& error)
- {
- log("WebSocket (%p) onError", ws);
- }
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。