SocketIO.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221
  1. /****************************************************************************
  2. Copyright (c) 2015 Chris Hannon http://www.channon.us
  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. *based on the SocketIO library created by LearnBoost at http://socket.io
  22. *using spec version 1 found at https://github.com/LearnBoost/socket.io-spec
  23. ****************************************************************************/
  24. #include "network/SocketIO.h"
  25. #include "network/Uri.h"
  26. #include <algorithm>
  27. #include <sstream>
  28. #include <iterator>
  29. #include "base/ccUTF8.h"
  30. #include "base/CCDirector.h"
  31. #include "base/CCScheduler.h"
  32. #include "network/WebSocket.h"
  33. #include "network/HttpClient.h"
  34. #include "json/rapidjson.h"
  35. #include "json/document-wrapper.h"
  36. #include "json/stringbuffer.h"
  37. #include "json/writer.h"
  38. NS_CC_BEGIN
  39. namespace network {
  40. //class declarations
  41. class SocketIOPacketV10x;
  42. class SocketIOPacket
  43. {
  44. public:
  45. enum class SocketIOVersion
  46. {
  47. V09x,
  48. V10x
  49. };
  50. SocketIOPacket();
  51. virtual ~SocketIOPacket();
  52. void initWithType(const std::string& packetType);
  53. void initWithTypeIndex(int index);
  54. std::string toString()const;
  55. virtual int typeAsNumber()const;
  56. const std::string& typeForIndex(int index)const;
  57. void setEndpoint(const std::string& endpoint){ _endpoint = endpoint; };
  58. const std::string& getEndpoint()const{ return _endpoint; };
  59. void setEvent(const std::string& event){ _name = event; };
  60. const std::string& getEvent()const{ return _name; };
  61. void addData(const std::string& data);
  62. std::vector<std::string> getData()const{ return _args; };
  63. virtual std::string stringify()const;
  64. static SocketIOPacket * createPacketWithType(const std::string& type, SocketIOVersion version);
  65. static SocketIOPacket * createPacketWithTypeIndex(int type, SocketIOVersion version);
  66. protected:
  67. std::string _pId;//id message
  68. std::string _ack;//
  69. std::string _name;//event name
  70. std::vector<std::string> _args;//we will be using a vector of strings to store multiple data
  71. std::string _endpoint;//
  72. std::string _endpointseparator;//socket.io 1.x requires a ',' between endpoint and payload
  73. std::string _type;//message type
  74. std::string _separator;//for stringify the object
  75. std::vector<std::string> _types;//types of messages
  76. };
  77. class SocketIOPacketV10x : public SocketIOPacket
  78. {
  79. public:
  80. SocketIOPacketV10x();
  81. virtual ~SocketIOPacketV10x();
  82. int typeAsNumber()const override;
  83. std::string stringify()const override;
  84. private:
  85. std::vector<std::string> _typesMessage;
  86. };
  87. SocketIOPacket::SocketIOPacket() :_endpointseparator(""), _separator(":")
  88. {
  89. _types.push_back("disconnect");
  90. _types.push_back("connect");
  91. _types.push_back("heartbeat");
  92. _types.push_back("message");
  93. _types.push_back("json");
  94. _types.push_back("event");
  95. _types.push_back("ack");
  96. _types.push_back("error");
  97. _types.push_back("noop");
  98. }
  99. SocketIOPacket::~SocketIOPacket()
  100. {
  101. _types.clear();
  102. }
  103. void SocketIOPacket::initWithType(const std::string& packetType)
  104. {
  105. _type = packetType;
  106. }
  107. void SocketIOPacket::initWithTypeIndex(int index)
  108. {
  109. _type = _types.at(index);
  110. }
  111. std::string SocketIOPacket::toString()const
  112. {
  113. std::stringstream encoded;
  114. encoded << this->typeAsNumber();
  115. encoded << this->_separator;
  116. std::string pIdL = _pId;
  117. if (_ack == "data")
  118. {
  119. pIdL += "+";
  120. }
  121. // Do not write pid for acknowledgements
  122. if (_type != "ack")
  123. {
  124. encoded << pIdL;
  125. }
  126. encoded << this->_separator;
  127. // Add the endpoint for the namespace to be used if not the default namespace "" or "/", and as long as it is not an ACK, heartbeat, or disconnect packet
  128. if (_endpoint != "/" && _endpoint != "" && _type != "ack" && _type != "heartbeat" && _type != "disconnect") {
  129. encoded << _endpoint << _endpointseparator;
  130. }
  131. encoded << this->_separator;
  132. if (!_args.empty())
  133. {
  134. std::string ackpId = "";
  135. // This is an acknowledgement packet, so, prepend the ack pid to the data
  136. if (_type == "ack")
  137. {
  138. ackpId += pIdL + "+";
  139. }
  140. encoded << ackpId << this->stringify();
  141. }
  142. return encoded.str();
  143. }
  144. int SocketIOPacket::typeAsNumber()const
  145. {
  146. std::string::size_type num = 0;
  147. auto item = std::find(_types.begin(), _types.end(), _type);
  148. if (item != _types.end())
  149. {
  150. num = item - _types.begin();
  151. }
  152. return (int)num;
  153. }
  154. const std::string& SocketIOPacket::typeForIndex(int index)const
  155. {
  156. return _types.at(index);
  157. }
  158. void SocketIOPacket::addData(const std::string& data)
  159. {
  160. this->_args.push_back(data);
  161. }
  162. std::string SocketIOPacket::stringify()const
  163. {
  164. std::string outS;
  165. if (_type == "message")
  166. {
  167. outS = _args[0];
  168. }
  169. else
  170. {
  171. rapidjson::StringBuffer s;
  172. rapidjson::Writer<rapidjson::StringBuffer> writer(s);
  173. writer.StartObject();
  174. writer.String("name");
  175. writer.String(_name.c_str());
  176. writer.String("args");
  177. writer.StartArray();
  178. for (auto& item : _args)
  179. {
  180. writer.String(item.c_str());
  181. }
  182. writer.EndArray();
  183. writer.EndObject();
  184. outS = s.GetString();
  185. CCLOGINFO("create args object: %s:", outS.c_str());
  186. }
  187. return outS;
  188. }
  189. SocketIOPacketV10x::SocketIOPacketV10x()
  190. {
  191. _separator = "";
  192. _endpointseparator = ",";
  193. _types.push_back("disconnected");
  194. _types.push_back("connected");
  195. _types.push_back("heartbeat");
  196. _types.push_back("pong");
  197. _types.push_back("message");
  198. _types.push_back("upgrade");
  199. _types.push_back("noop");
  200. _typesMessage.push_back("connect");
  201. _typesMessage.push_back("disconnect");
  202. _typesMessage.push_back("event");
  203. _typesMessage.push_back("ack");
  204. _typesMessage.push_back("error");
  205. _typesMessage.push_back("binarevent");
  206. _typesMessage.push_back("binaryack");
  207. }
  208. int SocketIOPacketV10x::typeAsNumber()const
  209. {
  210. std::vector<std::string>::size_type num = 0;
  211. auto item = std::find(_typesMessage.begin(), _typesMessage.end(), _type);
  212. if (item != _typesMessage.end())
  213. {//it's a message
  214. num = item - _typesMessage.begin();
  215. num += 40;
  216. }
  217. else
  218. {
  219. item = std::find(_types.begin(), _types.end(), _type);
  220. num += item - _types.begin();
  221. }
  222. return (int)num;
  223. }
  224. std::string SocketIOPacketV10x::stringify()const
  225. {
  226. std::string outS;
  227. rapidjson::StringBuffer s;
  228. rapidjson::Writer<rapidjson::StringBuffer> writer(s);
  229. writer.StartArray();
  230. writer.String(_name.c_str());
  231. for (auto& item : _args)
  232. {
  233. writer.String(item.c_str());
  234. }
  235. writer.EndArray();
  236. outS = s.GetString();
  237. CCLOGINFO("create args object: %s:", outS.c_str());
  238. return outS;
  239. }
  240. SocketIOPacketV10x::~SocketIOPacketV10x()
  241. {
  242. _types.clear();
  243. _typesMessage.clear();
  244. _type = "";
  245. _pId = "";
  246. _name = "";
  247. _ack = "";
  248. _endpoint = "";
  249. }
  250. SocketIOPacket * SocketIOPacket::createPacketWithType(const std::string& type, SocketIOPacket::SocketIOVersion version)
  251. {
  252. SocketIOPacket *ret;
  253. switch (version)
  254. {
  255. case SocketIOPacket::SocketIOVersion::V09x:
  256. ret = new (std::nothrow) SocketIOPacket;
  257. break;
  258. case SocketIOPacket::SocketIOVersion::V10x:
  259. ret = new (std::nothrow) SocketIOPacketV10x;
  260. break;
  261. }
  262. ret->initWithType(type);
  263. return ret;
  264. }
  265. SocketIOPacket * SocketIOPacket::createPacketWithTypeIndex(int type, SocketIOPacket::SocketIOVersion version)
  266. {
  267. SocketIOPacket *ret;
  268. switch (version)
  269. {
  270. case SocketIOPacket::SocketIOVersion::V09x:
  271. ret = new (std::nothrow) SocketIOPacket;
  272. break;
  273. case SocketIOPacket::SocketIOVersion::V10x:
  274. return new (std::nothrow) SocketIOPacketV10x;
  275. break;
  276. }
  277. ret->initWithTypeIndex(type);
  278. return ret;
  279. }
  280. /**
  281. * @brief The implementation of the socket.io connection
  282. * Clients/endpoints may share the same impl to accomplish multiplexing on the same websocket
  283. */
  284. class SIOClientImpl :
  285. public cocos2d::Ref,
  286. public WebSocket::Delegate
  287. {
  288. private:
  289. int _heartbeat, _timeout;
  290. std::string _sid;
  291. Uri _uri;
  292. std::string _caFilePath;
  293. bool _connected;
  294. SocketIOPacket::SocketIOVersion _version;
  295. WebSocket *_ws;
  296. Map<std::string, SIOClient*> _clients;
  297. public:
  298. SIOClientImpl(const Uri& uri, const std::string& caFilePath);
  299. virtual ~SIOClientImpl();
  300. static SIOClientImpl* create(const Uri& uri, const std::string& caFilePath);
  301. virtual void onOpen(WebSocket* ws);
  302. virtual void onMessage(WebSocket* ws, const WebSocket::Data& data);
  303. virtual void onClose(WebSocket* ws);
  304. virtual void onError(WebSocket* ws, const WebSocket::ErrorCode& error);
  305. void connect();
  306. void disconnect();
  307. bool init();
  308. void handshake();
  309. void handshakeResponse(HttpClient *sender, HttpResponse *response);
  310. void openSocket();
  311. void heartbeat(float dt);
  312. SIOClient* getClient(const std::string& endpoint);
  313. void addClient(const std::string& endpoint, SIOClient* client);
  314. void connectToEndpoint(const std::string& endpoint);
  315. void disconnectFromEndpoint(const std::string& endpoint);
  316. void send(const std::string& endpoint, const std::string& s);
  317. void send(SocketIOPacket *packet);
  318. void emit(const std::string& endpoint, const std::string& eventname, const std::string& args);
  319. };
  320. //method implementations
  321. //begin SIOClientImpl methods
  322. SIOClientImpl::SIOClientImpl(const Uri& uri, const std::string& caFilePath) :
  323. _uri(uri),
  324. _caFilePath(caFilePath),
  325. _connected(false),
  326. _ws(nullptr)
  327. {
  328. }
  329. SIOClientImpl::~SIOClientImpl()
  330. {
  331. if (_connected)
  332. disconnect();
  333. CC_SAFE_DELETE(_ws);
  334. }
  335. void SIOClientImpl::handshake()
  336. {
  337. CCLOGINFO("SIOClientImpl::handshake() called");
  338. std::stringstream pre;
  339. if (_uri.isSecure())
  340. pre << "https://";
  341. else
  342. pre << "http://";
  343. pre << _uri.getAuthority() << "/socket.io/1/?EIO=2&transport=polling&b64=true";
  344. HttpRequest* request = new (std::nothrow) HttpRequest();
  345. request->setUrl(pre.str());
  346. request->setRequestType(HttpRequest::Type::GET);
  347. request->setResponseCallback(CC_CALLBACK_2(SIOClientImpl::handshakeResponse, this));
  348. request->setTag("handshake");
  349. CCLOGINFO("SIOClientImpl::handshake() waiting");
  350. if (_uri.isSecure() && !_caFilePath.empty())
  351. {
  352. HttpClient::getInstance()->setSSLVerification(_caFilePath);
  353. }
  354. HttpClient::getInstance()->send(request);
  355. request->release();
  356. return;
  357. }
  358. void SIOClientImpl::handshakeResponse(HttpClient* /*sender*/, HttpResponse *response)
  359. {
  360. CCLOGINFO("SIOClientImpl::handshakeResponse() called");
  361. if (0 != strlen(response->getHttpRequest()->getTag()))
  362. {
  363. CCLOGINFO("%s completed", response->getHttpRequest()->getTag());
  364. }
  365. long statusCode = response->getResponseCode();
  366. char statusString[64] = {};
  367. sprintf(statusString, "HTTP Status Code: %ld, tag = %s", statusCode, response->getHttpRequest()->getTag());
  368. CCLOGINFO("response code: %ld", statusCode);
  369. if (!response->isSucceed())
  370. {
  371. CCLOGERROR("SIOClientImpl::handshake() failed");
  372. CCLOGERROR("error buffer: %s", response->getErrorBuffer());
  373. for (auto& client : _clients)
  374. {
  375. client.second->getDelegate()->onError(client.second, response->getErrorBuffer());
  376. }
  377. return;
  378. }
  379. CCLOGINFO("SIOClientImpl::handshake() succeeded");
  380. std::vector<char> *buffer = response->getResponseData();
  381. std::stringstream s;
  382. s.str("");
  383. for (const auto& iter : *buffer)
  384. {
  385. s << iter;
  386. }
  387. CCLOGINFO("SIOClientImpl::handshake() dump data: %s", s.str().c_str());
  388. std::string res = s.str();
  389. std::string sid = "";
  390. int heartbeat = 0, timeout = 0;
  391. if (res.at(res.size() - 1) == '}') {
  392. CCLOGINFO("SIOClientImpl::handshake() Socket.IO 1.x detected");
  393. _version = SocketIOPacket::SocketIOVersion::V10x;
  394. // sample: 97:0{"sid":"GMkL6lzCmgMvMs9bAAAA","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":60000}
  395. std::string::size_type a, b;
  396. a = res.find('{');
  397. std::string temp = res.substr(a, res.size() - a);
  398. // find the sid
  399. a = temp.find(":");
  400. b = temp.find(",");
  401. sid = temp.substr(a + 2, b - (a + 3));
  402. temp = temp.erase(0, b + 1);
  403. // chomp past the upgrades
  404. b = temp.find(",");
  405. temp = temp.erase(0, b + 1);
  406. // get the pingInterval / heartbeat
  407. a = temp.find(":");
  408. b = temp.find(",");
  409. std::string heartbeat_str = temp.substr(a + 1, b - a);
  410. heartbeat = atoi(heartbeat_str.c_str()) / 1000;
  411. temp = temp.erase(0, b + 1);
  412. // get the timeout
  413. a = temp.find(":");
  414. b = temp.find("}");
  415. std::string timeout_str = temp.substr(a + 1, b - a);
  416. timeout = atoi(timeout_str.c_str()) / 1000;
  417. CCLOGINFO("done parsing 1.x");
  418. }
  419. else {
  420. CCLOGINFO("SIOClientImpl::handshake() Socket.IO 0.9.x detected");
  421. _version = SocketIOPacket::SocketIOVersion::V09x;
  422. // sample: 3GYzE9md2Ig-lm3cf8Rv:60:60:websocket,htmlfile,xhr-polling,jsonp-polling
  423. size_t pos = 0;
  424. pos = res.find(":");
  425. if (pos != std::string::npos)
  426. {
  427. sid = res.substr(0, pos);
  428. res.erase(0, pos + 1);
  429. }
  430. pos = res.find(":");
  431. if (pos != std::string::npos)
  432. {
  433. heartbeat = atoi(res.substr(pos + 1, res.size()).c_str());
  434. }
  435. pos = res.find(":");
  436. if (pos != std::string::npos)
  437. {
  438. timeout = atoi(res.substr(pos + 1, res.size()).c_str());
  439. }
  440. }
  441. _sid = sid;
  442. _heartbeat = heartbeat;
  443. _timeout = timeout;
  444. openSocket();
  445. return;
  446. }
  447. void SIOClientImpl::openSocket()
  448. {
  449. CCLOGINFO("SIOClientImpl::openSocket() called");
  450. std::stringstream s;
  451. if (_uri.isSecure())
  452. s << "wss://";
  453. else
  454. s << "ws://";
  455. switch (_version)
  456. {
  457. case SocketIOPacket::SocketIOVersion::V09x:
  458. s << _uri.getAuthority() << "/socket.io/1/websocket/" << _sid;
  459. break;
  460. case SocketIOPacket::SocketIOVersion::V10x:
  461. s << _uri.getAuthority() << "/socket.io/1/websocket/?EIO=2&transport=websocket&sid=" << _sid;
  462. break;
  463. }
  464. _ws = new (std::nothrow) WebSocket();
  465. if (!_ws->init(*this, s.str(), nullptr, _caFilePath))
  466. {
  467. CC_SAFE_DELETE(_ws);
  468. }
  469. return;
  470. }
  471. bool SIOClientImpl::init()
  472. {
  473. CCLOGINFO("SIOClientImpl::init() successful");
  474. return true;
  475. }
  476. void SIOClientImpl::connect()
  477. {
  478. this->handshake();
  479. }
  480. void SIOClientImpl::disconnect()
  481. {
  482. if(_ws->getReadyState() == WebSocket::State::OPEN)
  483. {
  484. std::string s, endpoint;
  485. s = "";
  486. endpoint = "";
  487. if (_version == SocketIOPacket::SocketIOVersion::V09x)
  488. s = "0::" + endpoint;
  489. else
  490. s = "41" + endpoint;
  491. _ws->send(s);
  492. }
  493. Director::getInstance()->getScheduler()->unscheduleAllForTarget(this);
  494. _connected = false;
  495. SocketIO::getInstance()->removeSocket(_uri.getAuthority());
  496. // Close websocket connection should be at last.
  497. _ws->close();
  498. }
  499. SIOClientImpl* SIOClientImpl::create(const Uri& uri, const std::string& caFilePath)
  500. {
  501. SIOClientImpl *s = new (std::nothrow) SIOClientImpl(uri, caFilePath);
  502. if (s && s->init())
  503. {
  504. return s;
  505. }
  506. return nullptr;
  507. }
  508. SIOClient* SIOClientImpl::getClient(const std::string& endpoint)
  509. {
  510. return _clients.at(endpoint);
  511. }
  512. void SIOClientImpl::addClient(const std::string& endpoint, SIOClient* client)
  513. {
  514. _clients.insert(endpoint, client);
  515. }
  516. void SIOClientImpl::connectToEndpoint(const std::string& endpoint)
  517. {
  518. SocketIOPacket *packet = SocketIOPacket::createPacketWithType("connect", _version);
  519. packet->setEndpoint(endpoint);
  520. this->send(packet);
  521. }
  522. void SIOClientImpl::disconnectFromEndpoint(const std::string& endpoint)
  523. {
  524. _clients.erase(endpoint);
  525. if (_clients.empty() || endpoint == "/")
  526. {
  527. CCLOGINFO("SIOClientImpl::disconnectFromEndpoint out of endpoints, checking for disconnect");
  528. if (_connected)
  529. this->disconnect();
  530. }
  531. else
  532. {
  533. std::string path = endpoint == "/" ? "" : endpoint;
  534. std::string s = "0::" + path;
  535. _ws->send(s);
  536. }
  537. }
  538. void SIOClientImpl::heartbeat(float /*dt*/)
  539. {
  540. SocketIOPacket *packet = SocketIOPacket::createPacketWithType("heartbeat", _version);
  541. this->send(packet);
  542. CCLOGINFO("Heartbeat sent");
  543. }
  544. void SIOClientImpl::send(const std::string& endpoint, const std::string& s)
  545. {
  546. switch (_version) {
  547. case SocketIOPacket::SocketIOVersion::V09x:
  548. {
  549. SocketIOPacket *packet = SocketIOPacket::createPacketWithType("message", _version);
  550. packet->setEndpoint(endpoint);
  551. packet->addData(s);
  552. this->send(packet);
  553. break;
  554. }
  555. case SocketIOPacket::SocketIOVersion::V10x:
  556. {
  557. this->emit(endpoint, "message", s);
  558. break;
  559. }
  560. }
  561. }
  562. void SIOClientImpl::send(SocketIOPacket *packet)
  563. {
  564. std::string req = packet->toString();
  565. if (_connected)
  566. {
  567. CCLOGINFO("-->SEND:%s", req.data());
  568. _ws->send(req.data());
  569. }
  570. else
  571. CCLOGINFO("Cant send the message (%s) because disconnected", req.c_str());
  572. }
  573. void SIOClientImpl::emit(const std::string& endpoint, const std::string& eventname, const std::string& args)
  574. {
  575. CCLOGINFO("Emitting event \"%s\"", eventname.c_str());
  576. SocketIOPacket *packet = SocketIOPacket::createPacketWithType("event", _version);
  577. packet->setEndpoint(endpoint == "/" ? "" : endpoint);
  578. packet->setEvent(eventname);
  579. packet->addData(args);
  580. this->send(packet);
  581. }
  582. void SIOClientImpl::onOpen(WebSocket* /*ws*/)
  583. {
  584. _connected = true;
  585. SocketIO::getInstance()->addSocket(_uri.getAuthority(), this);
  586. if (_version == SocketIOPacket::SocketIOVersion::V10x)
  587. {
  588. std::string s = "5";//That's a ping https://github.com/Automattic/engine.io-parser/blob/1b8e077b2218f4947a69f5ad18be2a512ed54e93/lib/index.js#L21
  589. _ws->send(s.data());
  590. }
  591. Director::getInstance()->getScheduler()->schedule(CC_SCHEDULE_SELECTOR(SIOClientImpl::heartbeat), this, (_heartbeat * .9f), false);
  592. for (auto& client : _clients)
  593. {
  594. client.second->onOpen();
  595. }
  596. CCLOGINFO("SIOClientImpl::onOpen socket connected!");
  597. }
  598. void SIOClientImpl::onMessage(WebSocket* /*ws*/, const WebSocket::Data& data)
  599. {
  600. CCLOGINFO("SIOClientImpl::onMessage received: %s", data.bytes);
  601. std::string payload = data.bytes;
  602. int control = atoi(payload.substr(0, 1).c_str());
  603. payload = payload.substr(1, payload.size() - 1);
  604. SIOClient *c = nullptr;
  605. switch (_version)
  606. {
  607. case SocketIOPacket::SocketIOVersion::V09x:
  608. {
  609. std::string msgid, endpoint, s_data, eventname;
  610. std::string::size_type pos, pos2;
  611. pos = payload.find(":");
  612. if (pos != std::string::npos)
  613. {
  614. payload.erase(0, pos + 1);
  615. }
  616. pos = payload.find(":");
  617. if (pos != std::string::npos)
  618. {
  619. msgid = atoi(payload.substr(0, pos + 1).c_str());
  620. }
  621. payload.erase(0, pos + 1);
  622. pos = payload.find(":");
  623. if (pos != std::string::npos)
  624. {
  625. endpoint = payload.substr(0, pos);
  626. payload.erase(0, pos + 1);
  627. }
  628. else
  629. {
  630. endpoint = payload;
  631. }
  632. if (endpoint == "") endpoint = "/";
  633. c = getClient(endpoint);
  634. s_data = payload;
  635. if (c == nullptr) CCLOGINFO("SIOClientImpl::onMessage client lookup returned nullptr");
  636. switch (control)
  637. {
  638. case 0:
  639. CCLOGINFO("Received Disconnect Signal for Endpoint: %s\n", endpoint.c_str());
  640. disconnectFromEndpoint(endpoint);
  641. c->fireEvent("disconnect", payload);
  642. break;
  643. case 1:
  644. CCLOGINFO("Connected to endpoint: %s \n", endpoint.c_str());
  645. if (c) {
  646. c->onConnect();
  647. c->fireEvent("connect", payload);
  648. }
  649. break;
  650. case 2:
  651. CCLOGINFO("Heartbeat received\n");
  652. break;
  653. case 3:
  654. CCLOGINFO("Message received: %s \n", s_data.c_str());
  655. if (c) c->getDelegate()->onMessage(c, s_data);
  656. if (c) c->fireEvent("message", s_data);
  657. break;
  658. case 4:
  659. CCLOGINFO("JSON Message Received: %s \n", s_data.c_str());
  660. if (c) c->getDelegate()->onMessage(c, s_data);
  661. if (c) c->fireEvent("json", s_data);
  662. break;
  663. case 5:
  664. CCLOGINFO("Event Received with data: %s \n", s_data.c_str());
  665. if (c)
  666. {
  667. eventname = "";
  668. pos = s_data.find(":");
  669. pos2 = s_data.find(",");
  670. if (pos2 > pos)
  671. {
  672. eventname = s_data.substr(pos + 2, pos2 - (pos + 3));
  673. s_data = s_data.substr(pos2 + 9, s_data.size() - (pos2 + 11));
  674. }
  675. c->fireEvent(eventname, s_data);
  676. }
  677. break;
  678. case 6:
  679. CCLOGINFO("Message Ack\n");
  680. break;
  681. case 7:
  682. CCLOGERROR("Error\n");
  683. //if (c) c->getDelegate()->onError(c, s_data);
  684. if (c) c->fireEvent("error", s_data);
  685. break;
  686. case 8:
  687. CCLOGINFO("Noop\n");
  688. break;
  689. }
  690. }
  691. break;
  692. case SocketIOPacket::SocketIOVersion::V10x:
  693. {
  694. switch (control)
  695. {
  696. case 0:
  697. CCLOGINFO("Not supposed to receive control 0 for websocket");
  698. CCLOGINFO("That's not good");
  699. break;
  700. case 1:
  701. CCLOGINFO("Not supposed to receive control 1 for websocket");
  702. break;
  703. case 2:
  704. CCLOGINFO("Ping received, send pong");
  705. payload = "3" + payload;
  706. _ws->send(payload);
  707. break;
  708. case 3:
  709. CCLOGINFO("Pong received");
  710. if (payload == "probe")
  711. {
  712. CCLOGINFO("Request Update");
  713. _ws->send("5");
  714. }
  715. break;
  716. case 4:
  717. {
  718. int control2 = payload.at(0) - '0';
  719. CCLOGINFO("Message code: [%i]", control2);
  720. std::string endpoint = "";
  721. std::string::size_type a = payload.find("/");
  722. std::string::size_type b = payload.find("[");
  723. if (b != std::string::npos)
  724. {
  725. if (a != std::string::npos && a < b)
  726. {
  727. //we have an endpoint and a payload
  728. endpoint = payload.substr(a, b - (a + 1));
  729. }
  730. }
  731. else if (a != std::string::npos) {
  732. //we have an endpoint with no payload
  733. endpoint = payload.substr(a, payload.size() - a);
  734. }
  735. // we didn't find and endpoint and we are in the default namespace
  736. if (endpoint == "") endpoint = "/";
  737. c = getClient(endpoint);
  738. payload = payload.substr(1);
  739. if (endpoint != "/") payload = payload.substr(endpoint.size());
  740. if (endpoint != "/" && payload != "") payload = payload.substr(1);
  741. switch (control2)
  742. {
  743. case 0:
  744. CCLOGINFO("Socket Connected");
  745. if (c) {
  746. c->onConnect();
  747. c->fireEvent("connect", payload);
  748. }
  749. break;
  750. case 1:
  751. CCLOGINFO("Socket Disconnected");
  752. disconnectFromEndpoint(endpoint);
  753. c->fireEvent("disconnect", payload);
  754. break;
  755. case 2:
  756. {
  757. CCLOGINFO("Event Received (%s)", payload.c_str());
  758. std::string::size_type payloadFirstSlashPos = payload.find("\"");
  759. std::string::size_type payloadSecondSlashPos = payload.substr(payloadFirstSlashPos + 1).find("\"");
  760. std::string eventname = payload.substr(payloadFirstSlashPos + 1,
  761. payloadSecondSlashPos - payloadFirstSlashPos + 1);
  762. CCLOGINFO("event name %s between %i and %i", eventname.c_str(),
  763. payloadFirstSlashPos, payloadSecondSlashPos);
  764. payload = payload.substr(payloadSecondSlashPos + 4,
  765. payload.size() - (payloadSecondSlashPos + 5));
  766. if (c) c->fireEvent(eventname, payload);
  767. if (c) c->getDelegate()->onMessage(c, payload);
  768. }
  769. break;
  770. case 3:
  771. CCLOGINFO("Message Ack");
  772. break;
  773. case 4:
  774. CCLOGERROR("Error");
  775. if (c) c->fireEvent("error", payload);
  776. break;
  777. case 5:
  778. CCLOGINFO("Binary Event");
  779. break;
  780. case 6:
  781. CCLOGINFO("Binary Ack");
  782. break;
  783. }
  784. }
  785. break;
  786. case 5:
  787. CCLOGINFO("Upgrade required");
  788. break;
  789. case 6:
  790. CCLOGINFO("Noop\n");
  791. break;
  792. }
  793. }
  794. break;
  795. }
  796. return;
  797. }
  798. void SIOClientImpl::onClose(WebSocket* /*ws*/)
  799. {
  800. if (!_clients.empty())
  801. {
  802. for (auto& client : _clients)
  803. {
  804. client.second->socketClosed();
  805. }
  806. // discard this client
  807. _connected = false;
  808. if (Director::getInstance())
  809. Director::getInstance()->getScheduler()->unscheduleAllForTarget(this);
  810. SocketIO::getInstance()->removeSocket(_uri.getAuthority());
  811. }
  812. this->release();
  813. }
  814. void SIOClientImpl::onError(WebSocket* /*ws*/, const WebSocket::ErrorCode& error)
  815. {
  816. CCLOGERROR("Websocket error received: %d", static_cast<int>(error));
  817. }
  818. //begin SIOClient methods
  819. SIOClient::SIOClient(const std::string& path, SIOClientImpl* impl, SocketIO::SIODelegate& delegate)
  820. : _path(path)
  821. , _connected(false)
  822. , _socket(impl)
  823. , _delegate(&delegate)
  824. {
  825. }
  826. SIOClient::~SIOClient()
  827. {
  828. if (_connected)
  829. {
  830. _socket->disconnectFromEndpoint(_path);
  831. }
  832. }
  833. void SIOClient::onOpen()
  834. {
  835. if (_path != "/")
  836. {
  837. _socket->connectToEndpoint(_path);
  838. }
  839. }
  840. void SIOClient::onConnect()
  841. {
  842. _connected = true;
  843. }
  844. void SIOClient::send(const std::string& s)
  845. {
  846. if (_connected)
  847. {
  848. _socket->send(_path, s);
  849. }
  850. else
  851. {
  852. _delegate->onError(this, "Client not yet connected");
  853. }
  854. }
  855. void SIOClient::emit(const std::string& eventname, const std::string& args)
  856. {
  857. if(_connected)
  858. {
  859. _socket->emit(_path, eventname, args);
  860. }
  861. else
  862. {
  863. _delegate->onError(this, "Client not yet connected");
  864. }
  865. }
  866. void SIOClient::disconnect()
  867. {
  868. _connected = false;
  869. _socket->disconnectFromEndpoint(_path);
  870. this->release();
  871. }
  872. void SIOClient::socketClosed()
  873. {
  874. _connected = false;
  875. _delegate->onClose(this);
  876. this->release();
  877. }
  878. void SIOClient::on(const std::string& eventName, SIOEvent e)
  879. {
  880. _eventRegistry[eventName] = e;
  881. }
  882. void SIOClient::fireEvent(const std::string& eventName, const std::string& data)
  883. {
  884. CCLOGINFO("SIOClient::fireEvent called with event name: %s and data: %s", eventName.c_str(), data.c_str());
  885. _delegate->fireEventToScript(this, eventName, data);
  886. if(_eventRegistry[eventName])
  887. {
  888. SIOEvent e = _eventRegistry[eventName];
  889. e(this, data);
  890. return;
  891. }
  892. CCLOGINFO("SIOClient::fireEvent no native event with name %s found", eventName.c_str());
  893. }
  894. void SIOClient::setTag(const char* tag)
  895. {
  896. _tag = tag;
  897. }
  898. //begin SocketIO methods
  899. SocketIO *SocketIO::_inst = nullptr;
  900. SocketIO::SocketIO()
  901. {
  902. }
  903. SocketIO::~SocketIO()
  904. {
  905. }
  906. SocketIO* SocketIO::getInstance()
  907. {
  908. if (nullptr == _inst)
  909. _inst = new (std::nothrow) SocketIO();
  910. return _inst;
  911. }
  912. void SocketIO::destroyInstance()
  913. {
  914. CC_SAFE_DELETE(_inst);
  915. }
  916. SIOClient* SocketIO::connect(SocketIO::SIODelegate& delegate, const std::string& uri)
  917. {
  918. return SocketIO::connect(uri, delegate);
  919. }
  920. SIOClient* SocketIO::connect(const std::string& uri, SocketIO::SIODelegate& delegate)
  921. {
  922. return SocketIO::connect(uri, delegate, "");
  923. }
  924. SIOClient* SocketIO::connect(const std::string& uri, SocketIO::SIODelegate& delegate, const std::string& caFilePath)
  925. {
  926. Uri uriObj = Uri::parse(uri);
  927. SIOClientImpl *socket = SocketIO::getInstance()->getSocket(uriObj.getAuthority());
  928. SIOClient *c = nullptr;
  929. std::string path = uriObj.getPath();
  930. if (path == "")
  931. path = "/";
  932. if (socket == nullptr)
  933. {
  934. //create a new socket, new client, connect
  935. socket = SIOClientImpl::create(uriObj, caFilePath);
  936. c = new (std::nothrow) SIOClient(path, socket, delegate);
  937. socket->addClient(path, c);
  938. socket->connect();
  939. }
  940. else
  941. {
  942. //check if already connected to endpoint, handle
  943. c = socket->getClient(path);
  944. if(c == nullptr)
  945. {
  946. c = new (std::nothrow) SIOClient(path, socket, delegate);
  947. socket->addClient(path, c);
  948. socket->connectToEndpoint(path);
  949. }
  950. else
  951. {
  952. CCLOG("SocketIO: disconnect previous client");
  953. c->disconnect();
  954. CCLOG("SocketIO: recreate a new socket, new client, connect");
  955. SIOClientImpl* newSocket = SIOClientImpl::create(uriObj, caFilePath);
  956. SIOClient *newC = new (std::nothrow) SIOClient(path, newSocket, delegate);
  957. newSocket->addClient(path, newC);
  958. newSocket->connect();
  959. return newC;
  960. }
  961. }
  962. return c;
  963. }
  964. SIOClientImpl* SocketIO::getSocket(const std::string& uri)
  965. {
  966. return _sockets.at(uri);
  967. }
  968. void SocketIO::addSocket(const std::string& uri, SIOClientImpl* socket)
  969. {
  970. _sockets.insert(uri, socket);
  971. }
  972. void SocketIO::removeSocket(const std::string& uri)
  973. {
  974. _sockets.erase(uri);
  975. }
  976. }
  977. NS_CC_END