SocketIO.cpp 32 KB

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