WebSocket.cpp 40 KB

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