PuzzleSDK
WebSocketTest.cpp
浏览该文件的文档.
1/****************************************************************************
2 Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
3
4 http://www.cocos2d-x.org
5
6 Permission is hereby granted, free of charge, to any person obtaining a copy
7 of this software and associated documentation files (the "Software"), to deal
8 in the Software without restriction, including without limitation the rights
9 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 copies of the Software, and to permit persons to whom the Software is
11 furnished to do so, subject to the following conditions:
12
13 The above copyright notice and this permission notice shall be included in
14 all copies or substantial portions of the Software.
15
16 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 THE SOFTWARE.
23 ****************************************************************************/
24
25#include "WebSocketTest.h"
26#include "../ExtensionsTest.h"
27#include "testResource.h"
28
29#include "WebSocketDelayTest.h"
30
33
34WebSocketTests::WebSocketTests()
35{
39}
40
42: _wsiSendText(nullptr)
43, _wsiSendBinary(nullptr)
44, _wsiError(nullptr)
45, _sendTextStatus(nullptr)
46, _sendBinaryStatus(nullptr)
47, _errorStatus(nullptr)
48, _sendTextTimes(0)
49, _sendBinaryTimes(0)
50{
51 auto winSize = Director::getInstance()->getWinSize();
52
53 const int MARGIN = 40;
54 const int SPACE = 35;
55
56 auto menuRequest = Menu::create();
57 menuRequest->setPosition(Vec2::ZERO);
58 addChild(menuRequest);
59
60 // Send Text
61 auto labelSendText = Label::createWithTTF("Send Text", "fonts/arial.ttf", 20);
62 auto itemSendText = MenuItemLabel::create(labelSendText, CC_CALLBACK_1(WebSocketTest::onMenuSendTextClicked, this));
63 itemSendText->setPosition(Vec2(winSize.width / 2, winSize.height - MARGIN - SPACE));
64 menuRequest->addChild(itemSendText);
65
66 labelSendText = Label::createWithTTF("Send Multiple Text", "fonts/arial.ttf", 20);
67 itemSendText = MenuItemLabel::create(labelSendText, CC_CALLBACK_1(WebSocketTest::onMenuSendMultipleTextClicked, this));
68 itemSendText->setPosition(Vec2(winSize.width / 2, winSize.height - MARGIN - 2 * SPACE));
69 menuRequest->addChild(itemSendText);
70
71 // Send Binary
72 auto labelSendBinary = Label::createWithTTF("Send Binary", "fonts/arial.ttf", 20);
73 auto itemSendBinary = MenuItemLabel::create(labelSendBinary, CC_CALLBACK_1(WebSocketTest::onMenuSendBinaryClicked, this));
74 itemSendBinary->setPosition(Vec2(winSize.width / 2, winSize.height - MARGIN - 3 * SPACE));
75 menuRequest->addChild(itemSendBinary);
76
77
78 // Send Text Status Label
79 _sendTextStatus = Label::createWithTTF("Send Text WS is waiting...", "fonts/arial.ttf", 16, Size(160, 100), TextHAlignment::CENTER, TextVAlignment::TOP);
80 _sendTextStatus->setAnchorPoint(Vec2(0, 0));
81 _sendTextStatus->setPosition(Vec2(VisibleRect::left().x, VisibleRect::rightBottom().y + 25));
82 this->addChild(_sendTextStatus);
83
84 // Send Binary Status Label
85 _sendBinaryStatus = Label::createWithTTF("Send Binary WS is waiting...", "fonts/arial.ttf", 16, Size(160, 100), TextHAlignment::CENTER, TextVAlignment::TOP);
86 _sendBinaryStatus->setAnchorPoint(Vec2(0, 0));
87 _sendBinaryStatus->setPosition(Vec2(VisibleRect::left().x + 160, VisibleRect::rightBottom().y + 25));
88 this->addChild(_sendBinaryStatus);
89
90 // Error Label
91 _errorStatus = Label::createWithTTF("Error WS is waiting...", "fonts/arial.ttf", 16, Size(160, 100), TextHAlignment::CENTER, TextVAlignment::TOP);
92 _errorStatus->setAnchorPoint(Vec2(0, 0));
93 _errorStatus->setPosition(Vec2(VisibleRect::left().x + 320, VisibleRect::rightBottom().y + 25));
94 this->addChild(_errorStatus);
95
96 auto startTestLabel = Label::createWithTTF("Start Test WebSocket", "fonts/arial.ttf", 16);
97 auto startTestItem = MenuItemLabel::create(startTestLabel, CC_CALLBACK_1(WebSocketTest::startTestCallback, this));
98 startTestItem->setPosition(Vec2(VisibleRect::center().x - 150, VisibleRect::bottom().y + 150));
99 _startTestMenu = Menu::create(startTestItem, nullptr);
100 _startTestMenu->setPosition(Vec2::ZERO);
101 this->addChild(_startTestMenu, 1);
102}
103
105{
106
107}
108
110{
111 if (_wsiSendText)
112 {
113 _wsiSendText->closeAsync();
114 }
115
116 if (_wsiSendBinary)
117 {
118 _wsiSendBinary->closeAsync();
119 }
120
121 if (_wsiError)
122 {
123 _wsiError->closeAsync();
124 }
125 Node::onExit();
126}
127
129{
130 removeChild(_startTestMenu);
131 _startTestMenu = nullptr;
132
133 _wsiSendText = new network::WebSocket();
134 _wsiSendBinary = new network::WebSocket();
135 _wsiError = new network::WebSocket();
136
137 std::vector<std::string> protocols;
138 protocols.push_back("myprotocol_1");
139 protocols.push_back("myprotocol_2");
140 if (!_wsiSendText->init(*this, "wss://echo.websocket.org", &protocols, "cacert.pem"))
141 {
142 CC_SAFE_DELETE(_wsiSendText);
143 }
144 else
145 {
146 retain(); // Retain self to avoid WebSocketTest instance be deleted immediately, it will be released in WebSocketTest::onClose.
147 }
148
149 protocols.erase(protocols.begin());
150 if (!_wsiSendBinary->init(*this, "wss://echo.websocket.org", &protocols, "cacert.pem"))
151 {
152 CC_SAFE_DELETE(_wsiSendBinary);
153 }
154 else
155 {
156 retain(); // Retain self to avoid WebSocketTest instance be deleted immediately, it will be released in WebSocketTest::onClose.
157 }
158
159 if (!_wsiError->init(*this, "ws://invalid.urlxxxxxxxx.com"))
160 {
161 CC_SAFE_DELETE(_wsiError);
162 }
163 else
164 {
165 retain(); // Retain self to avoid WebSocketTest instance be deleted immediately, it will be released in WebSocketTest::onClose.
166 }
167}
168
169// Delegate methods
170void WebSocketTest::onOpen(network::WebSocket* ws)
171{
172 char status[256] = {0};
173 sprintf(status, "Opened, url: %s, protocol: %s", ws->getUrl().c_str(), ws->getProtocol().c_str());
174
175 log("Websocket (%p) was opened, url: %s, protocol: %s", ws, ws->getUrl().c_str(), ws->getProtocol().c_str());
176 if (ws == _wsiSendText)
177 {
178 _sendTextStatus->setString(status);
179 }
180 else if (ws == _wsiSendBinary)
181 {
182 _sendBinaryStatus->setString(status);
183 }
184 else if (ws == _wsiError)
185 {
186 CCASSERT(0, "error test will never go here.");
187 }
188}
189
190void WebSocketTest::onMessage(network::WebSocket* ws, const network::WebSocket::Data& data)
191{
192 if (!data.isBinary)
193 {
195 char times[100] = {0};
196 sprintf(times, "%d", _sendTextTimes);
197 std::string textStr = std::string("response text msg: ")+data.bytes+", "+times;
198 log("%s", textStr.c_str());
199
200 _sendTextStatus->setString(textStr.c_str());
201 }
202 else
203 {
205 char times[100] = {0};
206 sprintf(times, "%d", _sendBinaryTimes);
207
208 std::string binaryStr = "response bin msg: ";
209
210 for (int i = 0; i < data.len; ++i) {
211 if (data.bytes[i] != '\0')
212 {
213 binaryStr += data.bytes[i];
214 }
215 else
216 {
217 binaryStr += "\'\\0\'";
218 }
219 }
220
221 binaryStr += std::string(", ")+times;
222 log("%s", binaryStr.c_str());
223 _sendBinaryStatus->setString(binaryStr.c_str());
224 }
225}
226
227void WebSocketTest::onClose(network::WebSocket* ws)
228{
229 log("onClose: websocket instance (%p) closed.", ws);
230 if (ws == _wsiSendText)
231 {
232 _wsiSendText = nullptr;
233 _sendTextStatus->setString("Send Text WS was closed");
234 }
235 else if (ws == _wsiSendBinary)
236 {
237 _wsiSendBinary = nullptr;
238 _sendBinaryStatus->setString("Send Binary WS was closed");
239 }
240 else if (ws == _wsiError)
241 {
242 _wsiError = nullptr;
243 _errorStatus->setString("Test invalid URL WS was closed");
244 }
245 // Delete websocket instance.
246 CC_SAFE_DELETE(ws);
247 log("WebSocketTest ref: %u", _referenceCount);
248 release();
249}
250
251void WebSocketTest::onError(network::WebSocket* ws, const network::WebSocket::ErrorCode& error)
252{
253 log("Error was fired, error code: %d", static_cast<int>(error));
254 char buf[100] = {0};
255 sprintf(buf, "An error was fired, code: %d", static_cast<int>(error));
256
257 if (ws == _wsiSendText)
258 {
259 _sendTextStatus->setString(buf);
260 }
261 else if (ws == _wsiSendBinary)
262 {
263 _sendBinaryStatus->setString(buf);
264 }
265 else if (ws == _wsiError)
266 {
267 _errorStatus->setString(buf);
268 }
269}
270
271// Menu Callbacks
272void WebSocketTest::onMenuSendTextClicked(cocos2d::Ref *sender)
273{
274 if (! _wsiSendText)
275 {
276 return;
277 }
278
279 if (_wsiSendText->getReadyState() == network::WebSocket::State::OPEN)
280 {
281 _sendTextStatus->setString("Send Text WS is waiting...");
282 _wsiSendText->send("Hello WebSocket, I'm a text message.");
283 }
284 else
285 {
286 std::string warningStr = "send text websocket instance wasn't ready...";
287 log("%s", warningStr.c_str());
288 _sendTextStatus->setString(warningStr.c_str());
289 }
290}
291
293{
294 if (! _wsiSendText)
295 {
296 return;
297 }
298
299 if (_wsiSendText->getReadyState() == network::WebSocket::State::OPEN)
300 {
301 _sendTextStatus->setString("Send Multiple Text WS is waiting...");
302 for (int index = 0; index < 15; ++index) {
303 _wsiSendText->send(StringUtils::format("Hello WebSocket, text message index:%d", index));
304 }
305 }
306 else
307 {
308 std::string warningStr = "send text websocket instance wasn't ready...";
309 log("%s", warningStr.c_str());
310 _sendTextStatus->setString(warningStr.c_str());
311 }
312}
313
315{
316 if (! _wsiSendBinary) {
317 return;
318 }
319
320 if (_wsiSendBinary->getReadyState() == network::WebSocket::State::OPEN)
321 {
322 _sendBinaryStatus->setString("Send Binary WS is waiting...");
323 char buf[] = "Hello WebSocket,\0 I'm\0 a\0 binary\0 message\0.";
324 _wsiSendBinary->send((unsigned char*)buf, sizeof(buf));
325 }
326 else
327 {
328 std::string warningStr = "send binary websocket instance wasn't ready...";
329 log("%s", warningStr.c_str());
330 _sendBinaryStatus->setString(warningStr.c_str());
331 }
332}
333
335: _wsiTest(nullptr)
336{
337 auto winSize = Director::getInstance()->getWinSize();
338
339 _wsiTest = new network::WebSocket();
340
341 if (!_wsiTest->init(*this, "ws://echo.websocket.org"))
342 {
343 delete _wsiTest;
344 _wsiTest = nullptr;
345 }
346
347 auto closeItem = MenuItemImage::create(s_pathClose, s_pathClose, [](Ref* sender){
348 Director::getInstance()->end();
349 });
350 closeItem->setPosition(VisibleRect::right().x / 2, VisibleRect::top().y * 2 / 3);
351
352 auto menu = Menu::create(closeItem, nullptr);
353 menu->setPosition(Vec2::ZERO);
354 addChild(menu, 1);
355
356 auto notifyLabel = Label::createWithTTF("See log window, when enter there's should have\n'Websocket opened' log,\nwhen close there's should have'websocket closed' log", "fonts/arial.ttf", 20);
357 notifyLabel->setPosition(VisibleRect::right().x / 2, VisibleRect::top().y / 3);
358 notifyLabel->setAlignment(TextHAlignment::CENTER);
359 addChild(notifyLabel, 1);
360}
361
363{
364 if (_wsiTest != nullptr)
365 {
366 _wsiTest->close();
367 }
368}
369
370// Delegate methods
371void WebSocketCloseTest::onOpen(network::WebSocket* ws)
372{
373 log("Websocket (%p) opened", ws);
374}
375
376void WebSocketCloseTest::onMessage(network::WebSocket* ws, const network::WebSocket::Data& data)
377{
378 log("Websocket get message from %p", ws);
379}
380
381void WebSocketCloseTest::onClose(network::WebSocket* ws)
382{
383 log("websocket (%p) closed.", ws);
384 if (ws == _wsiTest) {
385 _wsiTest = nullptr;
386 }
387 CC_SAFE_DELETE(ws);
388}
389
390void WebSocketCloseTest::onError(network::WebSocket* ws, const network::WebSocket::ErrorCode& error)
391{
392 log("Error was fired, error code: %d", static_cast<int>(error));
393}
394
#define ADD_TEST_CASE(__className__)
Definition: BaseTest.h:211
USING_NS_CC_EXT
USING_NS_CC
static cocos2d::Vec2 top()
Definition: VisibleRect.cpp:57
static cocos2d::Vec2 center()
Definition: VisibleRect.cpp:69
static cocos2d::Vec2 bottom()
Definition: VisibleRect.cpp:63
static cocos2d::Vec2 left()
Definition: VisibleRect.cpp:45
static cocos2d::Vec2 rightBottom()
Definition: VisibleRect.cpp:93
static cocos2d::Vec2 right()
Definition: VisibleRect.cpp:51
virtual void onClose(cocos2d::network::WebSocket *ws) override
virtual void onError(cocos2d::network::WebSocket *ws, const cocos2d::network::WebSocket::ErrorCode &error) override
virtual void onMessage(cocos2d::network::WebSocket *ws, const cocos2d::network::WebSocket::Data &data) override
cocos2d::network::WebSocket * _wsiTest
Definition: WebSocketTest.h:99
virtual void onOpen(cocos2d::network::WebSocket *ws) override
virtual ~WebSocketCloseTest()
cocos2d::network::WebSocket * _wsiError
Definition: WebSocketTest.h:70
cocos2d::Label * _sendBinaryStatus
Definition: WebSocketTest.h:73
void onMenuSendBinaryClicked(cocos2d::Ref *sender)
void onMenuSendTextClicked(cocos2d::Ref *sender)
cocos2d::network::WebSocket * _wsiSendText
Definition: WebSocketTest.h:68
cocos2d::Label * _errorStatus
Definition: WebSocketTest.h:74
cocos2d::network::WebSocket * _wsiSendBinary
Definition: WebSocketTest.h:69
virtual ~WebSocketTest()
cocos2d::Label * _sendTextStatus
Definition: WebSocketTest.h:72
virtual void onError(cocos2d::network::WebSocket *ws, const cocos2d::network::WebSocket::ErrorCode &error) override
void startTestCallback(cocos2d::Ref *sender)
void onMenuSendMultipleTextClicked(cocos2d::Ref *sender)
virtual void onExit() override
cocos2d::Menu * _startTestMenu
Definition: WebSocketTest.h:75
virtual void onOpen(cocos2d::network::WebSocket *ws) override
virtual void onMessage(cocos2d::network::WebSocket *ws, const cocos2d::network::WebSocket::Data &data) override
virtual void onClose(cocos2d::network::WebSocket *ws) override
static const char s_pathClose[]
Definition: testResource.h:55