SocketIO.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  1. /****************************************************************************
  2. Copyright (c) 2015 Chris Hannon http://www.channon.us
  3. Copyright (c) 2013-2017 Chukong Technologies Inc.
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. *based on the SocketIO library created by LearnBoost at http://socket.io
  20. *using spec version 1 found at https://github.com/LearnBoost/socket.io-spec
  21. Usage is described below, a full working example can be found in TestCpp under ExtionsTest/NetworkTest/SocketIOTest
  22. creating a new connection to a socket.io server running at localhost:3000
  23. SIOClient *client = SocketIO::connect(*delegate, "ws://localhost:3000");
  24. the connection process will begin and if successful delegate::onOpen will be called
  25. if the connection process results in an error, delegate::onError will be called with the err msg
  26. sending a message to the server
  27. client->send("Hello!");
  28. emitting an event to be handled by the server, argument json formatting is up to you
  29. client->emit("eventname", "[{\"arg\":\"value\"}]");
  30. registering an event callback, target should be a member function in a subclass of SIODelegate
  31. CC_CALLBACK_2 is used to wrap the callback with std::bind and store as an SIOEvent
  32. client->on("eventname", CC_CALLBACK_2(TargetClass::targetfunc, *targetclass_instance));
  33. event target function should match this pattern, *this pointer will be made available
  34. void TargetClass::targetfunc(SIOClient *, const std::string&)
  35. disconnect from the endpoint by calling disconnect(), onClose will be called on the delegate once complete
  36. in the onClose method the pointer should be set to NULL or used to connect to a new endpoint
  37. client->disconnect();
  38. ****************************************************************************/
  39. #ifndef __CC_SOCKETIO_H__
  40. #define __CC_SOCKETIO_H__
  41. #include <string>
  42. #include <unordered_map>
  43. #include "platform/CCPlatformMacros.h"
  44. #include "base/CCMap.h"
  45. /**
  46. * @addtogroup network
  47. * @{
  48. */
  49. NS_CC_BEGIN
  50. namespace network {
  51. //forward declarations
  52. class SIOClientImpl;
  53. class SIOClient;
  54. /**
  55. * Singleton and wrapper class to provide static creation method as well as registry of all sockets.
  56. *
  57. * @lua NA
  58. */
  59. class CC_DLL SocketIO
  60. {
  61. public:
  62. /**
  63. * Get instance of SocketIO.
  64. *
  65. * @return SocketIO* the instance of SocketIO.
  66. */
  67. static SocketIO* getInstance();
  68. static void destroyInstance();
  69. /**
  70. * The delegate class to process socket.io events.
  71. * @lua NA
  72. */
  73. class SIODelegate
  74. {
  75. public:
  76. /** Destructor of SIODelegate. */
  77. virtual ~SIODelegate() {}
  78. /**
  79. * This is kept for backwards compatibility, connect is now fired as a socket.io event "connect"
  80. *
  81. * This function would be called when the related SIOClient object receive messages that mean it have connected to endpoint successfully.
  82. *
  83. * @param client the connected SIOClient object.
  84. */
  85. virtual void onConnect(SIOClient* client) { CCLOG("SIODelegate onConnect fired"); };
  86. /**
  87. * This is kept for backwards compatibility, message is now fired as a socket.io event "message"
  88. *
  89. * This function would be called when the related SIOClient object receive message or json message.
  90. *
  91. * @param client the connected SIOClient object.
  92. * @param data the message,it could be json message
  93. */
  94. virtual void onMessage(SIOClient* client, const std::string& data) { CCLOG("SIODelegate onMessage fired with data: %s", data.c_str()); };
  95. /**
  96. * Pure virtual callback function, this function should be overridden by the subclass.
  97. *
  98. * This function would be called when the related SIOClient object disconnect or receive disconnect signal.
  99. *
  100. * @param client the connected SIOClient object.
  101. */
  102. virtual void onClose(SIOClient* client) = 0;
  103. /**
  104. * Pure virtual callback function, this function should be overridden by the subclass.
  105. *
  106. * This function would be called when the related SIOClient object receive error signal or didn't connect the endpoint but do some network operation, eg.,send and emit,etc.
  107. *
  108. * @param client the connected SIOClient object.
  109. * @param data the error message
  110. */
  111. virtual void onError(SIOClient* client, const std::string& data) = 0;
  112. /**
  113. * Fire event to script when the related SIOClient object receive the fire event signal.
  114. *
  115. * @param client the connected SIOClient object.
  116. * @param eventName the event's name.
  117. * @param data the event's data information.
  118. */
  119. virtual void fireEventToScript(SIOClient* client, const std::string& eventName, const std::string& data) { CCLOG("SIODelegate event '%s' fired with data: %s", eventName.c_str(), data.c_str()); };
  120. };
  121. /**
  122. * Static client creation method, similar to socketio.connect(uri) in JS.
  123. * @param uri the URI of the socket.io server.
  124. * @param delegate the delegate which want to receive events from the socket.io client.
  125. * @return SIOClient* an initialized SIOClient if connected successfully, otherwise nullptr.
  126. */
  127. static SIOClient* connect(const std::string& uri, SocketIO::SIODelegate& delegate);
  128. /**
  129. * Static client creation method, similar to socketio.connect(uri) in JS.
  130. * @param uri the URI of the socket.io server.
  131. * @param delegate the delegate which want to receive events from the socket.io client.
  132. * @param caFilePath The ca file path for wss connection
  133. * @return SIOClient* an initialized SIOClient if connected successfully, otherwise nullptr.
  134. */
  135. static SIOClient* connect(const std::string& uri, SocketIO::SIODelegate& delegate, const std::string& caFilePath);
  136. /**
  137. * Static client creation method, similar to socketio.connect(uri) in JS.
  138. * @param delegate the delegate which want to receive events from the socket.io client.
  139. * @param uri the URI of the socket.io server.
  140. * @return SIOClient* an initialized SIOClient if connected successfully, otherwise nullptr.
  141. */
  142. CC_DEPRECATED_ATTRIBUTE static SIOClient* connect(SocketIO::SIODelegate& delegate, const std::string& uri);
  143. private:
  144. SocketIO();
  145. virtual ~SocketIO();
  146. static SocketIO *_inst;
  147. cocos2d::Map<std::string, SIOClientImpl*> _sockets;
  148. SIOClientImpl* getSocket(const std::string& uri);
  149. void addSocket(const std::string& uri, SIOClientImpl* socket);
  150. void removeSocket(const std::string& uri);
  151. friend class SIOClientImpl;
  152. private:
  153. CC_DISALLOW_COPY_AND_ASSIGN(SocketIO)
  154. };
  155. //c++11 style callbacks entities will be created using CC_CALLBACK (which uses std::bind)
  156. typedef std::function<void(SIOClient*, const std::string&)> SIOEvent;
  157. //c++11 map to callbacks
  158. typedef std::unordered_map<std::string, SIOEvent> EventRegistry;
  159. /**
  160. * A single connection to a socket.io endpoint.
  161. *
  162. * @lua NA
  163. */
  164. class CC_DLL SIOClient
  165. : public cocos2d::Ref
  166. {
  167. private:
  168. friend class SocketIO; // Only SocketIO class could contruct a SIOClient instance.
  169. std::string _path, _tag;
  170. bool _connected;
  171. SIOClientImpl* _socket;
  172. SocketIO::SIODelegate* _delegate;
  173. EventRegistry _eventRegistry;
  174. void fireEvent(const std::string& eventName, const std::string& data);
  175. void onOpen();
  176. void onConnect();
  177. void socketClosed();
  178. friend class SIOClientImpl;
  179. /**
  180. * Constructor of SIOClient class.
  181. *
  182. * @param host the string that represent the host address.
  183. * @param port the int value represent the port number.
  184. * @param path the string that represent endpoint.
  185. * @param impl the SIOClientImpl object.
  186. * @param delegate the SIODelegate object.
  187. */
  188. SIOClient(const std::string& path, SIOClientImpl* impl, SocketIO::SIODelegate& delegate);
  189. /**
  190. * Destructor of SIOClient class.
  191. */
  192. virtual ~SIOClient();
  193. public:
  194. /**
  195. * Get the delegate for the client
  196. * @return the delegate object for the client
  197. */
  198. SocketIO::SIODelegate* getDelegate() { return _delegate; };
  199. /**
  200. * Disconnect from the endpoint, onClose will be called for the delegate when complete
  201. */
  202. void disconnect();
  203. /**
  204. * Send a message to the socket.io server.
  205. *
  206. * @param s message.
  207. */
  208. void send(const std::string& s);
  209. /**
  210. * Emit the eventname and the args to the endpoint that _path point to.
  211. * @param eventname
  212. * @param args
  213. */
  214. void emit(const std::string& eventname, const std::string& args);
  215. /**
  216. * Used to register a socket.io event callback.
  217. * Event argument should be passed using CC_CALLBACK2(&Base::function, this).
  218. * @param eventName the name of event.
  219. * @param e the callback function.
  220. */
  221. void on(const std::string& eventName, SIOEvent e);
  222. /**
  223. * Set tag of SIOClient.
  224. * The tag is used to distinguish the various SIOClient objects.
  225. * @param tag string object.
  226. */
  227. void setTag(const char* tag);
  228. /**
  229. * Get tag of SIOClient.
  230. * @return const char* the pointer point to the _tag.
  231. */
  232. const char* getTag()
  233. {
  234. return _tag.c_str();
  235. }
  236. };
  237. }
  238. NS_CC_END
  239. // end group
  240. /// @}
  241. #endif /* defined(__CC_JSB_SOCKETIO_H__) */