WebSocket.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329
  1. /****************************************************************************
  2. Copyright (c) 2010-2012 cocos2d-x.org
  3. Copyright (c) 2013-2017 Chukong Technologies Inc.
  4. http://www.cocos2d-x.org
  5. Permission is hereby granted, free of charge, to any person obtaining a copy
  6. of this software and associated documentation files (the "Software"), to deal
  7. in the Software without restriction, including without limitation the rights
  8. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. copies of the Software, and to permit persons to whom the Software is
  10. furnished to do so, subject to the following conditions:
  11. The above copyright notice and this permission notice shall be included in
  12. all copies or substantial portions of the Software.
  13. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  19. THE SOFTWARE.
  20. "[WebSocket module] is based in part on the work of the libwebsockets project
  21. (http://libwebsockets.org)"
  22. ****************************************************************************/
  23. #include "network/WebSocket.h"
  24. #include "network/Uri.h"
  25. #include "base/CCDirector.h"
  26. #include "base/CCScheduler.h"
  27. #include "base/CCEventDispatcher.h"
  28. #include "base/CCEventListenerCustom.h"
  29. #include "platform/CCFileUtils.h"
  30. #include <thread>
  31. #include <mutex>
  32. #include <queue>
  33. #include <list>
  34. #include <signal.h>
  35. #include <errno.h>
  36. #include "libwebsockets.h"
  37. #define NS_NETWORK_BEGIN namespace cocos2d { namespace network {
  38. #define NS_NETWORK_END }}
  39. #define WS_RX_BUFFER_SIZE (65536)
  40. #define WS_RESERVE_RECEIVE_BUFFER_SIZE (4096)
  41. #define LOG_TAG "WebSocket.cpp"
  42. #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
  43. // log, CCLOG aren't threadsafe, since we uses sub threads for parsing pcm data, threadsafe log output
  44. // is needed. Define the following macros (ALOGV, ALOGD, ALOGI, ALOGW, ALOGE) for threadsafe log output.
  45. //FIXME: Move _winLog, winLog to a separated file
  46. static void _winLog(const char *format, va_list args)
  47. {
  48. static const int MAX_LOG_LENGTH = 16 * 1024;
  49. int bufferSize = MAX_LOG_LENGTH;
  50. char* buf = nullptr;
  51. do
  52. {
  53. buf = new (std::nothrow) char[bufferSize];
  54. if (buf == nullptr)
  55. return; // not enough memory
  56. int ret = vsnprintf(buf, bufferSize - 3, format, args);
  57. if (ret < 0)
  58. {
  59. bufferSize *= 2;
  60. delete[] buf;
  61. }
  62. else
  63. break;
  64. } while (true);
  65. strcat(buf, "\n");
  66. int pos = 0;
  67. int len = strlen(buf);
  68. char tempBuf[MAX_LOG_LENGTH + 1] = { 0 };
  69. WCHAR wszBuf[MAX_LOG_LENGTH + 1] = { 0 };
  70. do
  71. {
  72. std::copy(buf + pos, buf + pos + MAX_LOG_LENGTH, tempBuf);
  73. tempBuf[MAX_LOG_LENGTH] = 0;
  74. MultiByteToWideChar(CP_UTF8, 0, tempBuf, -1, wszBuf, sizeof(wszBuf));
  75. OutputDebugStringW(wszBuf);
  76. pos += MAX_LOG_LENGTH;
  77. } while (pos < len);
  78. delete[] buf;
  79. }
  80. static void wsLog(const char * format, ...)
  81. {
  82. va_list args;
  83. va_start(args, format);
  84. _winLog(format, args);
  85. va_end(args);
  86. }
  87. #else
  88. #define wsLog printf
  89. #endif
  90. #define QUOTEME_(x) #x
  91. #define QUOTEME(x) QUOTEME_(x)
  92. // Since CCLOG isn't thread safe, we uses LOGD for multi-thread logging.
  93. #ifdef ANDROID
  94. #if COCOS2D_DEBUG > 0
  95. #define LOGD(...) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG,__VA_ARGS__)
  96. #else
  97. #define LOGD(...)
  98. #endif
  99. #define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG,__VA_ARGS__)
  100. #else
  101. #if COCOS2D_DEBUG > 0
  102. #define LOGD(fmt, ...) wsLog("D/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__)
  103. #else
  104. #define LOGD(fmt, ...)
  105. #endif
  106. #define LOGE(fmt, ...) wsLog("E/" LOG_TAG " (" QUOTEME(__LINE__) "): " fmt "", ##__VA_ARGS__)
  107. #endif
  108. static void printWebSocketLog(int level, const char *line)
  109. {
  110. #if COCOS2D_DEBUG > 0
  111. static const char * const log_level_names[] = {
  112. "ERR",
  113. "WARN",
  114. "NOTICE",
  115. "INFO",
  116. "DEBUG",
  117. "PARSER",
  118. "HEADER",
  119. "EXTENSION",
  120. "CLIENT",
  121. "LATENCY",
  122. };
  123. char buf[30] = {0};
  124. int n;
  125. for (n = 0; n < LLL_COUNT; n++) {
  126. if (level != (1 << n))
  127. continue;
  128. sprintf(buf, "%s: ", log_level_names[n]);
  129. break;
  130. }
  131. LOGD("%s%s\n", buf, line);
  132. #endif // #if COCOS2D_DEBUG > 0
  133. }
  134. NS_NETWORK_BEGIN
  135. enum WS_MSG {
  136. WS_MSG_TO_SUBTRHEAD_SENDING_STRING = 0,
  137. WS_MSG_TO_SUBTRHEAD_SENDING_BINARY,
  138. WS_MSG_TO_SUBTHREAD_CREATE_CONNECTION
  139. };
  140. static std::vector<WebSocket*>* __websocketInstances = nullptr;
  141. static std::mutex __instanceMutex;
  142. static struct lws_context* __wsContext = nullptr;
  143. static WsThreadHelper* __wsHelper = nullptr;
  144. #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
  145. static std::string getFileNameForPath(const std::string& filePath)
  146. {
  147. std::string fileName = filePath;
  148. const size_t lastSlashIdx = fileName.find_last_of("\\/");
  149. if (std::string::npos != lastSlashIdx)
  150. {
  151. fileName.erase(0, lastSlashIdx + 1);
  152. }
  153. return fileName;
  154. }
  155. #endif
  156. static struct lws_protocols __defaultProtocols[2];
  157. static lws_context_creation_info convertToContextCreationInfo(const struct lws_protocols* protocols, bool peerServerCert)
  158. {
  159. lws_context_creation_info info;
  160. memset(&info, 0, sizeof(info));
  161. /*
  162. * create the websocket context. This tracks open connections and
  163. * knows how to route any traffic and which protocol version to use,
  164. * and if each connection is client or server side.
  165. *
  166. * For this client-only demo, we tell it to not listen on any port.
  167. */
  168. info.port = CONTEXT_PORT_NO_LISTEN;
  169. info.protocols = protocols;
  170. // FIXME: Disable 'permessage-deflate' extension temporarily because of issues:
  171. // https://github.com/cocos2d/cocos2d-x/issues/16045, https://github.com/cocos2d/cocos2d-x/issues/15767
  172. // libwebsockets issue: https://github.com/warmcat/libwebsockets/issues/593
  173. // Currently, we couldn't find out the exact reason.
  174. // libwebsockets official said it's probably an issue of user code
  175. // since 'libwebsockets' passed AutoBahn stressed Test.
  176. // info.extensions = exts;
  177. info.gid = -1;
  178. info.uid = -1;
  179. if (peerServerCert)
  180. {
  181. info.options = LWS_SERVER_OPTION_EXPLICIT_VHOSTS | LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT;
  182. }
  183. else
  184. {
  185. info.options = LWS_SERVER_OPTION_EXPLICIT_VHOSTS | LWS_SERVER_OPTION_DO_SSL_GLOBAL_INIT | LWS_SERVER_OPTION_PEER_CERT_NOT_REQUIRED;
  186. }
  187. info.user = nullptr;
  188. return info;
  189. }
  190. class WsMessage
  191. {
  192. public:
  193. WsMessage() : id(++__id), what(0), data(nullptr), user(nullptr){}
  194. unsigned int id;
  195. unsigned int what; // message type
  196. void* data;
  197. void* user;
  198. private:
  199. static unsigned int __id;
  200. };
  201. unsigned int WsMessage::__id = 0;
  202. /**
  203. * @brief Websocket thread helper, it's used for sending message between UI thread and websocket thread.
  204. */
  205. class WsThreadHelper
  206. {
  207. public:
  208. WsThreadHelper();
  209. ~WsThreadHelper();
  210. // Creates a new thread
  211. bool createWebSocketThread();
  212. // Quits websocket thread.
  213. void quitWebSocketThread();
  214. // Sends message to Cocos thread. It's needed to be invoked in Websocket thread.
  215. void sendMessageToCocosThread(const std::function<void()>& cb);
  216. // Sends message to Websocket thread. It's needs to be invoked in Cocos thread.
  217. void sendMessageToWebSocketThread(WsMessage *msg);
  218. // Waits the sub-thread (websocket thread) to exit,
  219. void joinWebSocketThread();
  220. void onSubThreadStarted();
  221. void onSubThreadLoop();
  222. void onSubThreadEnded();
  223. protected:
  224. void wsThreadEntryFunc();
  225. public:
  226. std::list<WsMessage*>* _subThreadWsMessageQueue;
  227. std::mutex _subThreadWsMessageQueueMutex;
  228. std::thread* _subThreadInstance;
  229. private:
  230. bool _needQuit;
  231. };
  232. // Wrapper for converting websocket callback from static function to member function of WebSocket class.
  233. class WebSocketCallbackWrapper {
  234. public:
  235. static int onSocketCallback(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len)
  236. {
  237. // Gets the user data from context. We know that it's a 'WebSocket' instance.
  238. if (wsi == nullptr) {
  239. return 0;
  240. }
  241. int ret = 0;
  242. WebSocket* ws = (WebSocket*)lws_wsi_user(wsi);
  243. if (ws != nullptr && __websocketInstances != nullptr)
  244. {
  245. if (std::find(__websocketInstances->begin(), __websocketInstances->end(), ws) != __websocketInstances->end())
  246. {
  247. ret = ws->onSocketCallback(wsi, reason, in, len);
  248. }
  249. }
  250. else
  251. {
  252. // LOGD("ws instance is nullptr.\n");
  253. }
  254. return ret;
  255. }
  256. };
  257. // Implementation of WsThreadHelper
  258. WsThreadHelper::WsThreadHelper()
  259. : _subThreadInstance(nullptr)
  260. , _needQuit(false)
  261. {
  262. _subThreadWsMessageQueue = new (std::nothrow) std::list<WsMessage*>();
  263. }
  264. WsThreadHelper::~WsThreadHelper()
  265. {
  266. joinWebSocketThread();
  267. CC_SAFE_DELETE(_subThreadInstance);
  268. delete _subThreadWsMessageQueue;
  269. }
  270. bool WsThreadHelper::createWebSocketThread()
  271. {
  272. // Creates websocket thread
  273. _subThreadInstance = new (std::nothrow) std::thread(&WsThreadHelper::wsThreadEntryFunc, this);
  274. return true;
  275. }
  276. void WsThreadHelper::quitWebSocketThread()
  277. {
  278. _needQuit = true;
  279. }
  280. void WsThreadHelper::onSubThreadLoop()
  281. {
  282. if (__wsContext)
  283. {
  284. // _readyStateMutex.unlock();
  285. __wsHelper->_subThreadWsMessageQueueMutex.lock();
  286. bool isEmpty = __wsHelper->_subThreadWsMessageQueue->empty();
  287. if (!isEmpty)
  288. {
  289. auto iter = __wsHelper->_subThreadWsMessageQueue->begin();
  290. for (; iter != __wsHelper->_subThreadWsMessageQueue->end(); )
  291. {
  292. auto msg = (*iter);
  293. auto ws = (WebSocket*)msg->user;
  294. // TODO: ws may be a invalid pointer
  295. if (msg->what == WS_MSG_TO_SUBTHREAD_CREATE_CONNECTION)
  296. {
  297. ws->onClientOpenConnectionRequest();
  298. delete *iter;
  299. iter = __wsHelper->_subThreadWsMessageQueue->erase(iter);
  300. }
  301. else
  302. {
  303. ++iter;
  304. }
  305. }
  306. }
  307. __wsHelper->_subThreadWsMessageQueueMutex.unlock();
  308. // The second parameter passed to 'lws_service' means the timeout in milliseconds while polling websocket events.
  309. // The lower value the better, otherwise, it may trigger high CPU usage.
  310. // We set 2ms in 'lws_service' then sleep 3ms to make lower CPU cost.
  311. // Since messages are received in websocket thread and user code is in cocos thread, we need to post event to
  312. // cocos thread and trigger user callbacks by 'Scheduler::performFunctionInCocosThread'. If game's fps is set
  313. // to 60 (16.66ms), the latency will be (2ms + 3ms + 16.66ms + internet delay) > 21ms
  314. lws_service(__wsContext, 2);
  315. std::this_thread::sleep_for(std::chrono::milliseconds(3));
  316. }
  317. }
  318. void WsThreadHelper::onSubThreadStarted()
  319. {
  320. int log_level = LLL_ERR | LLL_WARN | LLL_NOTICE | LLL_INFO/* | LLL_DEBUG | LLL_PARSER | LLL_HEADER*/ | LLL_EXT | LLL_CLIENT | LLL_LATENCY;
  321. lws_set_log_level(log_level, printWebSocketLog);
  322. memset(__defaultProtocols, 0, sizeof(2 * sizeof(struct lws_protocols)));
  323. __defaultProtocols[0].name = "";
  324. __defaultProtocols[0].callback = WebSocketCallbackWrapper::onSocketCallback;
  325. __defaultProtocols[0].rx_buffer_size = WS_RX_BUFFER_SIZE;
  326. __defaultProtocols[0].id = std::numeric_limits<uint32_t>::max();
  327. lws_context_creation_info creationInfo = convertToContextCreationInfo(__defaultProtocols, true);
  328. __wsContext = lws_create_context(&creationInfo);
  329. }
  330. void WsThreadHelper::onSubThreadEnded()
  331. {
  332. if (__wsContext != nullptr)
  333. {
  334. lws_context_destroy(__wsContext);
  335. }
  336. }
  337. void WsThreadHelper::wsThreadEntryFunc()
  338. {
  339. LOGD("WebSocket thread start, helper instance: %p\n", this);
  340. onSubThreadStarted();
  341. while (!_needQuit)
  342. {
  343. onSubThreadLoop();
  344. }
  345. onSubThreadEnded();
  346. LOGD("WebSocket thread exit, helper instance: %p\n", this);
  347. }
  348. void WsThreadHelper::sendMessageToCocosThread(const std::function<void()>& cb)
  349. {
  350. Director::getInstance()->getScheduler()->performFunctionInCocosThread(cb);
  351. }
  352. void WsThreadHelper::sendMessageToWebSocketThread(WsMessage *msg)
  353. {
  354. std::lock_guard<std::mutex> lk(_subThreadWsMessageQueueMutex);
  355. _subThreadWsMessageQueue->push_back(msg);
  356. }
  357. void WsThreadHelper::joinWebSocketThread()
  358. {
  359. if (_subThreadInstance->joinable())
  360. {
  361. _subThreadInstance->join();
  362. }
  363. }
  364. // Define a WebSocket frame
  365. class WebSocketFrame
  366. {
  367. public:
  368. WebSocketFrame()
  369. : _payload(nullptr)
  370. , _payloadLength(0)
  371. , _frameLength(0)
  372. {
  373. }
  374. bool init(unsigned char* buf, ssize_t len)
  375. {
  376. if (buf == nullptr && len > 0)
  377. return false;
  378. if (!_data.empty())
  379. {
  380. LOGD("WebSocketFrame was initialized, should not init it again!\n");
  381. return false;
  382. }
  383. _data.reserve(LWS_PRE + len);
  384. _data.resize(LWS_PRE, 0x00);
  385. if (len > 0)
  386. {
  387. _data.insert(_data.end(), buf, buf + len);
  388. }
  389. _payload = _data.data() + LWS_PRE;
  390. _payloadLength = len;
  391. _frameLength = len;
  392. return true;
  393. }
  394. void update(ssize_t issued)
  395. {
  396. _payloadLength -= issued;
  397. _payload += issued;
  398. }
  399. unsigned char* getPayload() const { return _payload; }
  400. ssize_t getPayloadLength() const { return _payloadLength; }
  401. ssize_t getFrameLength() const { return _frameLength; }
  402. private:
  403. unsigned char* _payload;
  404. ssize_t _payloadLength;
  405. ssize_t _frameLength;
  406. std::vector<unsigned char> _data;
  407. };
  408. //
  409. void WebSocket::closeAllConnections()
  410. {
  411. if (__websocketInstances != nullptr)
  412. {
  413. ssize_t count = __websocketInstances->size();
  414. for (ssize_t i = count-1; i >=0 ; i--)
  415. {
  416. WebSocket* instance = __websocketInstances->at(i);
  417. instance->close();
  418. }
  419. std::lock_guard<std::mutex> lk(__instanceMutex);
  420. __websocketInstances->clear();
  421. delete __websocketInstances;
  422. __websocketInstances = nullptr;
  423. }
  424. }
  425. WebSocket::WebSocket()
  426. : _readyState(State::CONNECTING)
  427. , _wsInstance(nullptr)
  428. , _lwsProtocols(nullptr)
  429. , _isDestroyed(std::make_shared<std::atomic<bool>>(false))
  430. , _delegate(nullptr)
  431. , _closeState(CloseState::NONE)
  432. {
  433. // reserve data buffer to avoid allocate memory frequently
  434. _receivedData.reserve(WS_RESERVE_RECEIVE_BUFFER_SIZE);
  435. if (__websocketInstances == nullptr)
  436. {
  437. __websocketInstances = new (std::nothrow) std::vector<WebSocket*>();
  438. }
  439. __websocketInstances->push_back(this);
  440. std::shared_ptr<std::atomic<bool>> isDestroyed = _isDestroyed;
  441. _resetDirectorListener = Director::getInstance()->getEventDispatcher()->addCustomEventListener(Director::EVENT_RESET, [this, isDestroyed](EventCustom*){
  442. if (*isDestroyed)
  443. return;
  444. close();
  445. });
  446. }
  447. WebSocket::~WebSocket()
  448. {
  449. LOGD("In the destructor of WebSocket (%p)\n", this);
  450. std::lock_guard<std::mutex> lk(__instanceMutex);
  451. if (__websocketInstances != nullptr)
  452. {
  453. auto iter = std::find(__websocketInstances->begin(), __websocketInstances->end(), this);
  454. if (iter != __websocketInstances->end())
  455. {
  456. __websocketInstances->erase(iter);
  457. }
  458. else
  459. {
  460. LOGD("ERROR: WebSocket instance (%p) wasn't added to the container which saves websocket instances!\n", this);
  461. }
  462. }
  463. if (__websocketInstances == nullptr || __websocketInstances->empty())
  464. {
  465. __wsHelper->quitWebSocketThread();
  466. LOGD("before join ws thread\n");
  467. __wsHelper->joinWebSocketThread();
  468. LOGD("after join ws thread\n");
  469. CC_SAFE_DELETE(__wsHelper);
  470. }
  471. Director::getInstance()->getEventDispatcher()->removeEventListener(_resetDirectorListener);
  472. *_isDestroyed = true;
  473. }
  474. bool WebSocket::init(const Delegate& delegate,
  475. const std::string& url,
  476. const std::vector<std::string>* protocols/* = nullptr*/,
  477. const std::string& caFilePath/* = ""*/)
  478. {
  479. _delegate = const_cast<Delegate*>(&delegate);
  480. _url = url;
  481. _caFilePath = caFilePath;
  482. if (_url.empty())
  483. return false;
  484. if (protocols != nullptr && !protocols->empty())
  485. {
  486. size_t size = protocols->size();
  487. _lwsProtocols = (struct lws_protocols*)malloc((size + 1) * sizeof(struct lws_protocols));
  488. memset(_lwsProtocols, 0, (size + 1) * sizeof(struct lws_protocols));
  489. static uint32_t __wsId = 0;
  490. for (size_t i = 0; i < size; ++i)
  491. {
  492. _lwsProtocols[i].callback = WebSocketCallbackWrapper::onSocketCallback;
  493. size_t nameLen = protocols->at(i).length();
  494. char* name = (char*)malloc(nameLen + 1);
  495. name[nameLen] = '\0';
  496. strcpy(name, protocols->at(i).c_str());
  497. _lwsProtocols[i].name = name;
  498. _lwsProtocols[i].id = ++__wsId;
  499. _lwsProtocols[i].rx_buffer_size = WS_RX_BUFFER_SIZE;
  500. _lwsProtocols[i].per_session_data_size = 0;
  501. _lwsProtocols[i].user = nullptr;
  502. _clientSupportedProtocols += name;
  503. if (i < (size - 1))
  504. {
  505. _clientSupportedProtocols += ",";
  506. }
  507. }
  508. }
  509. bool isWebSocketThreadCreated = true;
  510. if (__wsHelper == nullptr)
  511. {
  512. __wsHelper = new (std::nothrow) WsThreadHelper();
  513. isWebSocketThreadCreated = false;
  514. }
  515. WsMessage* msg = new (std::nothrow) WsMessage();
  516. msg->what = WS_MSG_TO_SUBTHREAD_CREATE_CONNECTION;
  517. msg->user = this;
  518. __wsHelper->sendMessageToWebSocketThread(msg);
  519. // fixed https://github.com/cocos2d/cocos2d-x/issues/17433
  520. // createWebSocketThread has to be after message WS_MSG_TO_SUBTHREAD_CREATE_CONNECTION was sent.
  521. // And websocket thread should only be created once.
  522. if (!isWebSocketThreadCreated)
  523. {
  524. __wsHelper->createWebSocketThread();
  525. }
  526. return true;
  527. }
  528. void WebSocket::send(const std::string& message)
  529. {
  530. if (_readyState == State::OPEN)
  531. {
  532. // In main thread
  533. Data* data = new (std::nothrow) Data();
  534. data->bytes = (char*)malloc(message.length() + 1);
  535. // Make sure the last byte is '\0'
  536. data->bytes[message.length()] = '\0';
  537. strcpy(data->bytes, message.c_str());
  538. data->len = static_cast<ssize_t>(message.length());
  539. WsMessage* msg = new (std::nothrow) WsMessage();
  540. msg->what = WS_MSG_TO_SUBTRHEAD_SENDING_STRING;
  541. msg->data = data;
  542. msg->user = this;
  543. __wsHelper->sendMessageToWebSocketThread(msg);
  544. }
  545. else
  546. {
  547. LOGD("Couldn't send message since websocket wasn't opened!\n");
  548. }
  549. }
  550. void WebSocket::send(const unsigned char* binaryMsg, unsigned int len)
  551. {
  552. if (_readyState == State::OPEN)
  553. {
  554. // In main thread
  555. Data* data = new (std::nothrow) Data();
  556. if (len == 0)
  557. {
  558. // If data length is zero, allocate 1 byte for safe.
  559. data->bytes = (char*)malloc(1);
  560. data->bytes[0] = '\0';
  561. }
  562. else
  563. {
  564. data->bytes = (char*)malloc(len);
  565. memcpy((void*)data->bytes, (void*)binaryMsg, len);
  566. }
  567. data->len = len;
  568. WsMessage* msg = new (std::nothrow) WsMessage();
  569. msg->what = WS_MSG_TO_SUBTRHEAD_SENDING_BINARY;
  570. msg->data = data;
  571. msg->user = this;
  572. __wsHelper->sendMessageToWebSocketThread(msg);
  573. }
  574. else
  575. {
  576. LOGD("Couldn't send message since websocket wasn't opened!\n");
  577. }
  578. }
  579. void WebSocket::close()
  580. {
  581. if (_closeState != CloseState::NONE)
  582. {
  583. LOGD("close was invoked, don't invoke it again!\n");
  584. return;
  585. }
  586. _closeState = CloseState::SYNC_CLOSING;
  587. LOGD("close: WebSocket (%p) is closing...\n", this);
  588. {
  589. _readyStateMutex.lock();
  590. if (_readyState == State::CLOSED)
  591. {
  592. // If readState is closed, it means that onConnectionClosed was invoked in websocket thread,
  593. // but the callback of performInCocosThread has not been triggered. We need to invoke
  594. // onClose to release the websocket instance.
  595. _readyStateMutex.unlock();
  596. _delegate->onClose(this);
  597. return;
  598. }
  599. _readyState = State::CLOSING;
  600. _readyStateMutex.unlock();
  601. }
  602. {
  603. std::unique_lock<std::mutex> lkClose(_closeMutex);
  604. _closeCondition.wait(lkClose);
  605. _closeState = CloseState::SYNC_CLOSED;
  606. }
  607. // Wait 5 milliseconds for onConnectionClosed to exit!
  608. std::this_thread::sleep_for(std::chrono::milliseconds(5));
  609. _delegate->onClose(this);
  610. }
  611. void WebSocket::closeAsync()
  612. {
  613. if (_closeState != CloseState::NONE)
  614. {
  615. LOGD("close was invoked, don't invoke it again!\n");
  616. return;
  617. }
  618. _closeState = CloseState::ASYNC_CLOSING;
  619. LOGD("closeAsync: WebSocket (%p) is closing...\n", this);
  620. std::lock_guard<std::mutex> lk(_readyStateMutex);
  621. if (_readyState == State::CLOSED || _readyState == State::CLOSING)
  622. {
  623. LOGD("closeAsync: WebSocket (%p) was closed, no need to close it again!\n", this);
  624. return;
  625. }
  626. _readyState = State::CLOSING;
  627. }
  628. WebSocket::State WebSocket::getReadyState()
  629. {
  630. std::lock_guard<std::mutex> lk(_readyStateMutex);
  631. return _readyState;
  632. }
  633. struct lws_vhost* WebSocket::createVhost(struct lws_protocols* protocols, int& sslConnection)
  634. {
  635. auto fileUtils = FileUtils::getInstance();
  636. bool isCAFileExist = fileUtils->isFileExist(_caFilePath);
  637. if (isCAFileExist)
  638. {
  639. _caFilePath = fileUtils->fullPathForFilename(_caFilePath);
  640. }
  641. lws_context_creation_info info = convertToContextCreationInfo(protocols, isCAFileExist);
  642. if (sslConnection != 0)
  643. {
  644. if (isCAFileExist)
  645. {
  646. #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
  647. // if ca file is in the apk, try to extract it to writable path
  648. std::string writablePath = fileUtils->getWritablePath();
  649. std::string caFileName = getFileNameForPath(_caFilePath);
  650. std::string newCaFilePath = writablePath + caFileName;
  651. if (fileUtils->isFileExist(newCaFilePath))
  652. {
  653. LOGD("CA file (%s) in writable path exists!", newCaFilePath.c_str());
  654. _caFilePath = newCaFilePath;
  655. info.ssl_ca_filepath = _caFilePath.c_str();
  656. }
  657. else
  658. {
  659. if (fileUtils->isFileExist(_caFilePath))
  660. {
  661. std::string fullPath = fileUtils->fullPathForFilename(_caFilePath);
  662. LOGD("Found CA file: %s", fullPath.c_str());
  663. if (fullPath[0] != '/')
  664. {
  665. LOGD("CA file is in APK");
  666. auto caData = fileUtils->getDataFromFile(fullPath);
  667. if (!caData.isNull())
  668. {
  669. FILE* fp = fopen(newCaFilePath.c_str(), "wb");
  670. if (fp != nullptr)
  671. {
  672. LOGD("New CA file path: %s", newCaFilePath.c_str());
  673. fwrite(caData.getBytes(), caData.getSize(), 1, fp);
  674. fclose(fp);
  675. _caFilePath = newCaFilePath;
  676. info.ssl_ca_filepath = _caFilePath.c_str();
  677. }
  678. else
  679. {
  680. CCASSERT(false, "Open new CA file failed");
  681. }
  682. }
  683. else
  684. {
  685. CCASSERT(false, "CA file is empty!");
  686. }
  687. }
  688. else
  689. {
  690. LOGD("CA file isn't in APK!");
  691. _caFilePath = fullPath;
  692. info.ssl_ca_filepath = _caFilePath.c_str();
  693. }
  694. }
  695. else
  696. {
  697. CCASSERT(false, "CA file doesn't exist!");
  698. }
  699. }
  700. #else
  701. info.ssl_ca_filepath = _caFilePath.c_str();
  702. #endif
  703. }
  704. else
  705. {
  706. LOGD("WARNING: CA Root file isn't set. SSL connection will not peer server certificate\n");
  707. sslConnection = sslConnection | LCCSCF_ALLOW_SELFSIGNED | LCCSCF_SKIP_SERVER_CERT_HOSTNAME_CHECK;
  708. }
  709. }
  710. lws_vhost* vhost = lws_create_vhost(__wsContext, &info);
  711. return vhost;
  712. }
  713. void WebSocket::onClientOpenConnectionRequest()
  714. {
  715. if (nullptr != __wsContext)
  716. {
  717. static const struct lws_extension exts[] = {
  718. {
  719. "permessage-deflate",
  720. lws_extension_callback_pm_deflate,
  721. // client_no_context_takeover extension is not supported in the current version, it will cause connection fail
  722. // It may be a bug of lib websocket build
  723. // "permessage-deflate; client_no_context_takeover; client_max_window_bits"
  724. "permessage-deflate; client_max_window_bits"
  725. },
  726. {
  727. "deflate-frame",
  728. lws_extension_callback_pm_deflate,
  729. "deflate_frame"
  730. },
  731. { nullptr, nullptr, nullptr /* terminator */ }
  732. };
  733. _readyStateMutex.lock();
  734. _readyState = State::CONNECTING;
  735. _readyStateMutex.unlock();
  736. Uri uri = Uri::parse(_url);
  737. LOGD("scheme: %s, host: %s, port: %d, path: %s\n", uri.getScheme().c_str(), uri.getHostName().c_str(), static_cast<int>(uri.getPort()), uri.getPathEtc().c_str());
  738. int sslConnection = 0;
  739. if (uri.isSecure())
  740. sslConnection = LCCSCF_USE_SSL;
  741. struct lws_vhost* vhost = nullptr;
  742. if (_lwsProtocols != nullptr)
  743. {
  744. vhost = createVhost(_lwsProtocols, sslConnection);
  745. }
  746. else
  747. {
  748. vhost = createVhost(__defaultProtocols, sslConnection);
  749. }
  750. int port = static_cast<int>(uri.getPort());
  751. if (port == 0)
  752. port = uri.isSecure() ? 443 : 80;
  753. const std::string& hostName = uri.getHostName();
  754. std::string path = uri.getPathEtc();
  755. const std::string& authority = uri.getAuthority();
  756. if (path.empty())
  757. path = "/";
  758. struct lws_client_connect_info connectInfo;
  759. memset(&connectInfo, 0, sizeof(connectInfo));
  760. connectInfo.context = __wsContext;
  761. connectInfo.address = hostName.c_str();
  762. connectInfo.port = port;
  763. connectInfo.ssl_connection = sslConnection;
  764. connectInfo.path = path.c_str();
  765. connectInfo.host = hostName.c_str();
  766. connectInfo.origin = authority.c_str();
  767. connectInfo.protocol = _clientSupportedProtocols.empty() ? nullptr : _clientSupportedProtocols.c_str();
  768. connectInfo.ietf_version_or_minus_one = -1;
  769. connectInfo.userdata = this;
  770. connectInfo.client_exts = exts;
  771. connectInfo.vhost = vhost;
  772. _wsInstance = lws_client_connect_via_info(&connectInfo);
  773. if (nullptr == _wsInstance)
  774. {
  775. onConnectionError();
  776. return;
  777. }
  778. }
  779. else
  780. {
  781. LOGE("Create websocket context failed!");
  782. }
  783. }
  784. int WebSocket::onClientWritable()
  785. {
  786. // LOGD("onClientWritable ... \n");
  787. {
  788. std::lock_guard<std::mutex> readMutex(_readyStateMutex);
  789. if (_readyState == State::CLOSING)
  790. {
  791. LOGD("Closing websocket (%p) connection.\n", this);
  792. return -1;
  793. }
  794. }
  795. do
  796. {
  797. std::lock_guard<std::mutex> lk(__wsHelper->_subThreadWsMessageQueueMutex);
  798. if (__wsHelper->_subThreadWsMessageQueue->empty())
  799. {
  800. break;
  801. }
  802. std::list<WsMessage*>::iterator iter = __wsHelper->_subThreadWsMessageQueue->begin();
  803. while (iter != __wsHelper->_subThreadWsMessageQueue->end())
  804. {
  805. WsMessage* msg = *iter;
  806. if (msg->user == this)
  807. {
  808. break;
  809. }
  810. else
  811. {
  812. ++iter;
  813. }
  814. }
  815. ssize_t bytesWrite = 0;
  816. if (iter != __wsHelper->_subThreadWsMessageQueue->end())
  817. {
  818. WsMessage* subThreadMsg = *iter;
  819. Data* data = (Data*)subThreadMsg->data;
  820. const ssize_t c_bufferSize = WS_RX_BUFFER_SIZE;
  821. const ssize_t remaining = data->len - data->issued;
  822. const ssize_t n = std::min(remaining, c_bufferSize);
  823. WebSocketFrame* frame = nullptr;
  824. if (data->ext)
  825. {
  826. frame = (WebSocketFrame*)data->ext;
  827. }
  828. else
  829. {
  830. frame = new (std::nothrow) WebSocketFrame();
  831. bool success = frame && frame->init((unsigned char*)(data->bytes + data->issued), n);
  832. if (success)
  833. {
  834. data->ext = frame;
  835. }
  836. else
  837. { // If frame initialization failed, delete the frame and drop the sending data
  838. // These codes should never be called.
  839. LOGD("WebSocketFrame initialization failed, drop the sending data, msg(%d)\n", (int)subThreadMsg->id);
  840. delete frame;
  841. CC_SAFE_FREE(data->bytes);
  842. CC_SAFE_DELETE(data);
  843. __wsHelper->_subThreadWsMessageQueue->erase(iter);
  844. CC_SAFE_DELETE(subThreadMsg);
  845. break;
  846. }
  847. }
  848. int writeProtocol;
  849. if (data->issued == 0)
  850. {
  851. if (WS_MSG_TO_SUBTRHEAD_SENDING_STRING == subThreadMsg->what)
  852. {
  853. writeProtocol = LWS_WRITE_TEXT;
  854. }
  855. else
  856. {
  857. writeProtocol = LWS_WRITE_BINARY;
  858. }
  859. // If we have more than 1 fragment
  860. if (data->len > c_bufferSize)
  861. writeProtocol |= LWS_WRITE_NO_FIN;
  862. } else {
  863. // we are in the middle of fragments
  864. writeProtocol = LWS_WRITE_CONTINUATION;
  865. // and if not in the last fragment
  866. if (remaining != n)
  867. writeProtocol |= LWS_WRITE_NO_FIN;
  868. }
  869. bytesWrite = lws_write(_wsInstance, frame->getPayload(), frame->getPayloadLength(), (lws_write_protocol)writeProtocol);
  870. // Handle the result of lws_write
  871. // Buffer overrun?
  872. if (bytesWrite < 0)
  873. {
  874. LOGD("ERROR: msg(%u), lws_write return: %d, but it should be %d, drop this message.\n", subThreadMsg->id, (int)bytesWrite, (int)n);
  875. // socket error, we need to close the socket connection
  876. CC_SAFE_FREE(data->bytes);
  877. delete ((WebSocketFrame*)data->ext);
  878. data->ext = nullptr;
  879. CC_SAFE_DELETE(data);
  880. __wsHelper->_subThreadWsMessageQueue->erase(iter);
  881. CC_SAFE_DELETE(subThreadMsg);
  882. closeAsync();
  883. }
  884. else if (bytesWrite < frame->getPayloadLength())
  885. {
  886. frame->update(bytesWrite);
  887. LOGD("frame wasn't sent completely, bytesWrite: %d, remain: %d\n", (int)bytesWrite, (int)frame->getPayloadLength());
  888. }
  889. // Do we have another fragments to send?
  890. else if (remaining > frame->getFrameLength() && bytesWrite == frame->getPayloadLength())
  891. {
  892. // A frame was totally sent, plus data->issued to send next frame
  893. LOGD("msg(%u) append: %d + %d = %d\n", subThreadMsg->id, (int)data->issued, (int)frame->getFrameLength(), (int)(data->issued + frame->getFrameLength()));
  894. data->issued += frame->getFrameLength();
  895. delete ((WebSocketFrame*)data->ext);
  896. data->ext = nullptr;
  897. }
  898. // Safely done!
  899. else
  900. {
  901. LOGD("Safely done, msg(%d)!\n", subThreadMsg->id);
  902. if (remaining == frame->getFrameLength())
  903. {
  904. LOGD("msg(%u) append: %d + %d = %d\n", subThreadMsg->id, (int)data->issued, (int)frame->getFrameLength(), (int)(data->issued + frame->getFrameLength()));
  905. LOGD("msg(%u) was totally sent!\n", subThreadMsg->id);
  906. }
  907. else
  908. {
  909. LOGD("ERROR: msg(%u), remaining(%d) < bytesWrite(%d)\n", subThreadMsg->id, (int)remaining, (int)frame->getFrameLength());
  910. LOGD("Drop the msg(%u)\n", subThreadMsg->id);
  911. closeAsync();
  912. }
  913. CC_SAFE_FREE(data->bytes);
  914. delete ((WebSocketFrame*)data->ext);
  915. data->ext = nullptr;
  916. CC_SAFE_DELETE(data);
  917. __wsHelper->_subThreadWsMessageQueue->erase(iter);
  918. CC_SAFE_DELETE(subThreadMsg);
  919. LOGD("-----------------------------------------------------------\n");
  920. }
  921. }
  922. } while(false);
  923. if (_wsInstance != nullptr)
  924. {
  925. lws_callback_on_writable(_wsInstance);
  926. }
  927. return 0;
  928. }
  929. int WebSocket::onClientReceivedData(void* in, ssize_t len)
  930. {
  931. // In websocket thread
  932. static int packageIndex = 0;
  933. packageIndex++;
  934. if (in != nullptr && len > 0)
  935. {
  936. LOGD("Receiving data:index:%d, len=%d\n", packageIndex, (int)len);
  937. unsigned char* inData = (unsigned char*)in;
  938. _receivedData.insert(_receivedData.end(), inData, inData + len);
  939. }
  940. else
  941. {
  942. LOGD("Empty message received, index=%d!\n", packageIndex);
  943. }
  944. // If no more data pending, send it to the client thread
  945. size_t remainingSize = lws_remaining_packet_payload(_wsInstance);
  946. int isFinalFragment = lws_is_final_fragment(_wsInstance);
  947. // LOGD("remainingSize: %d, isFinalFragment: %d\n", (int)remainingSize, isFinalFragment);
  948. if (remainingSize == 0 && isFinalFragment)
  949. {
  950. std::vector<char>* frameData = new (std::nothrow) std::vector<char>(std::move(_receivedData));
  951. // reset capacity of received data buffer
  952. _receivedData.reserve(WS_RESERVE_RECEIVE_BUFFER_SIZE);
  953. ssize_t frameSize = frameData->size();
  954. bool isBinary = (lws_frame_is_binary(_wsInstance) != 0);
  955. if (!isBinary)
  956. {
  957. frameData->push_back('\0');
  958. }
  959. std::shared_ptr<std::atomic<bool>> isDestroyed = _isDestroyed;
  960. __wsHelper->sendMessageToCocosThread([this, frameData, frameSize, isBinary, isDestroyed](){
  961. // In UI thread
  962. LOGD("Notify data len %d to Cocos thread.\n", (int)frameSize);
  963. Data data;
  964. data.isBinary = isBinary;
  965. data.bytes = (char*)frameData->data();
  966. data.len = frameSize;
  967. if (*isDestroyed)
  968. {
  969. LOGD("WebSocket instance was destroyed!\n");
  970. }
  971. else
  972. {
  973. _delegate->onMessage(this, data);
  974. }
  975. delete frameData;
  976. });
  977. }
  978. return 0;
  979. }
  980. int WebSocket::onConnectionOpened()
  981. {
  982. const lws_protocols* lwsSelectedProtocol = lws_get_protocol(_wsInstance);
  983. _selectedProtocol = lwsSelectedProtocol->name;
  984. LOGD("onConnectionOpened...: %p, client protocols: %s, server selected protocol: %s\n", this, _clientSupportedProtocols.c_str(), _selectedProtocol.c_str());
  985. /*
  986. * start the ball rolling,
  987. * LWS_CALLBACK_CLIENT_WRITEABLE will come next service
  988. */
  989. lws_callback_on_writable(_wsInstance);
  990. {
  991. std::lock_guard<std::mutex> lk(_readyStateMutex);
  992. if (_readyState == State::CLOSING || _readyState == State::CLOSED)
  993. {
  994. return 0;
  995. }
  996. _readyState = State::OPEN;
  997. }
  998. std::shared_ptr<std::atomic<bool>> isDestroyed = _isDestroyed;
  999. __wsHelper->sendMessageToCocosThread([this, isDestroyed](){
  1000. if (*isDestroyed)
  1001. {
  1002. LOGD("WebSocket instance was destroyed!\n");
  1003. }
  1004. else
  1005. {
  1006. _delegate->onOpen(this);
  1007. }
  1008. });
  1009. return 0;
  1010. }
  1011. int WebSocket::onConnectionError()
  1012. {
  1013. {
  1014. std::lock_guard<std::mutex> lk(_readyStateMutex);
  1015. LOGD("WebSocket (%p) onConnectionError, state: %d ...\n", this, (int)_readyState);
  1016. if (_readyState == State::CLOSED)
  1017. {
  1018. return 0;
  1019. }
  1020. _readyState = State::CLOSING;
  1021. }
  1022. std::shared_ptr<std::atomic<bool>> isDestroyed = _isDestroyed;
  1023. __wsHelper->sendMessageToCocosThread([this, isDestroyed](){
  1024. if (*isDestroyed)
  1025. {
  1026. LOGD("WebSocket instance was destroyed!\n");
  1027. }
  1028. else
  1029. {
  1030. _delegate->onError(this, ErrorCode::CONNECTION_FAILURE);
  1031. }
  1032. });
  1033. onConnectionClosed();
  1034. return 0;
  1035. }
  1036. int WebSocket::onConnectionClosed()
  1037. {
  1038. {
  1039. std::lock_guard<std::mutex> lk(_readyStateMutex);
  1040. LOGD("WebSocket (%p) onConnectionClosed, state: %d ...\n", this, (int)_readyState);
  1041. if (_readyState == State::CLOSED)
  1042. {
  1043. return 0;
  1044. }
  1045. if (_readyState == State::CLOSING)
  1046. {
  1047. if (_closeState == CloseState::SYNC_CLOSING)
  1048. {
  1049. LOGD("onConnectionClosed, WebSocket (%p) is closing by client synchronously.\n", this);
  1050. for(;;)
  1051. {
  1052. std::lock_guard<std::mutex> lkClose(_closeMutex);
  1053. _closeCondition.notify_one();
  1054. if (_closeState == CloseState::SYNC_CLOSED)
  1055. {
  1056. break;
  1057. }
  1058. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  1059. }
  1060. return 0;
  1061. }
  1062. else if (_closeState == CloseState::ASYNC_CLOSING)
  1063. {
  1064. LOGD("onConnectionClosed, WebSocket (%p) is closing by client asynchronously.\n", this);
  1065. }
  1066. else
  1067. {
  1068. LOGD("onConnectionClosed, WebSocket (%p) is closing by server.\n", this);
  1069. }
  1070. }
  1071. else
  1072. {
  1073. LOGD("onConnectionClosed, WebSocket (%p) is closing by server.\n", this);
  1074. }
  1075. _readyState = State::CLOSED;
  1076. }
  1077. std::shared_ptr<std::atomic<bool>> isDestroyed = _isDestroyed;
  1078. __wsHelper->sendMessageToCocosThread([this, isDestroyed](){
  1079. if (*isDestroyed)
  1080. {
  1081. LOGD("WebSocket instance (%p) was destroyed!\n", this);
  1082. }
  1083. else
  1084. {
  1085. _delegate->onClose(this);
  1086. }
  1087. });
  1088. LOGD("WebSocket (%p) onConnectionClosed DONE!\n", this);
  1089. return 0;
  1090. }
  1091. int WebSocket::onSocketCallback(struct lws *wsi,
  1092. int reason,
  1093. void *in, ssize_t len)
  1094. {
  1095. //LOGD("socket callback for %d reason\n", reason);
  1096. int ret = 0;
  1097. switch (reason)
  1098. {
  1099. case LWS_CALLBACK_CLIENT_ESTABLISHED:
  1100. ret = onConnectionOpened();
  1101. break;
  1102. case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:
  1103. ret = onConnectionError();
  1104. break;
  1105. case LWS_CALLBACK_WSI_DESTROY:
  1106. ret = onConnectionClosed();
  1107. break;
  1108. case LWS_CALLBACK_CLIENT_RECEIVE:
  1109. ret = onClientReceivedData(in, len);
  1110. break;
  1111. case LWS_CALLBACK_CLIENT_WRITEABLE:
  1112. ret = onClientWritable();
  1113. break;
  1114. case LWS_CALLBACK_CHANGE_MODE_POLL_FD:
  1115. case LWS_CALLBACK_LOCK_POLL:
  1116. case LWS_CALLBACK_UNLOCK_POLL:
  1117. break;
  1118. case LWS_CALLBACK_PROTOCOL_INIT:
  1119. LOGD("protocol init...");
  1120. break;
  1121. case LWS_CALLBACK_PROTOCOL_DESTROY:
  1122. LOGD("protocol destroy...");
  1123. break;
  1124. default:
  1125. LOGD("WebSocket (%p) Unhandled websocket event: %d\n", this, reason);
  1126. break;
  1127. }
  1128. return ret;
  1129. }
  1130. NS_NETWORK_END