SocketIO.h 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  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. 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. Usage is described below, a full working example can be found in TestCpp under ExtionsTest/NetworkTest/SocketIOTest
  23. creating a new connection to a socket.io server running at localhost:3000
  24. SIOClient *client = SocketIO::connect(*delegate, "ws://localhost:3000");
  25. the connection process will begin and if successful delegate::onOpen will be called
  26. if the connection process results in an error, delegate::onError will be called with the err msg
  27. sending a message to the server
  28. client->send("Hello!");
  29. emitting an event to be handled by the server, argument json formatting is up to you
  30. client->emit("eventname", "[{\"arg\":\"value\"}]");
  31. registering an event callback, target should be a member function in a subclass of SIODelegate
  32. CC_CALLBACK_2 is used to wrap the callback with std::bind and store as an SIOEvent
  33. client->on("eventname", CC_CALLBACK_2(TargetClass::targetfunc, *targetclass_instance));
  34. event target function should match this pattern, *this pointer will be made available
  35. void TargetClass::targetfunc(SIOClient *, const std::string&)
  36. disconnect from the endpoint by calling disconnect(), onClose will be called on the delegate once complete
  37. in the onClose method the pointer should be set to NULL or used to connect to a new endpoint
  38. client->disconnect();
  39. ****************************************************************************/
  40. #ifndef __CC_SOCKETIO_H__
  41. #define __CC_SOCKETIO_H__
  42. #include <string>
  43. #include <unordered_map>
  44. #include "platform/CCPlatformMacros.h"
  45. #include "base/CCMap.h"
  46. /**
  47. * @addtogroup network
  48. * @{
  49. */
  50. NS_CC_BEGIN
  51. namespace network {
  52. //forward declarations
  53. class SIOClientImpl;
  54. class SIOClient;
  55. /**
  56. * Singleton and wrapper class to provide static creation method as well as registry of all sockets.
  57. *
  58. * @lua NA
  59. */
  60. class CC_DLL SocketIO
  61. {
  62. public:
  63. /**
  64. * Get instance of SocketIO.
  65. *
  66. * @return SocketIO* the instance of SocketIO.
  67. */
  68. static SocketIO* getInstance();
  69. static void destroyInstance();
  70. /**
  71. * The delegate class to process socket.io events.
  72. * @lua NA
  73. */
  74. class SIODelegate
  75. {
  76. public:
  77. /** Destructor of SIODelegate. */
  78. virtual ~SIODelegate() {}
  79. /**
  80. * This is kept for backwards compatibility, connect is now fired as a socket.io event "connect"
  81. *
  82. * This function would be called when the related SIOClient object receive messages that mean it have connected to endpoint successfully.
  83. *
  84. * @param client the connected SIOClient object.
  85. */
  86. virtual void onConnect(SIOClient* client) { CCLOG("SIODelegate onConnect fired"); };
  87. /**
  88. * This is kept for backwards compatibility, message is now fired as a socket.io event "message"
  89. *
  90. * This function would be called when the related SIOClient object receive message or json message.
  91. *
  92. * @param client the connected SIOClient object.
  93. * @param data the message,it could be json message
  94. */
  95. virtual void onMessage(SIOClient* client, const std::string& data) { CCLOG("SIODelegate onMessage fired with data: %s", data.c_str()); };
  96. /**
  97. * Pure virtual callback function, this function should be overridden by the subclass.
  98. *
  99. * This function would be called when the related SIOClient object disconnect or receive disconnect signal.
  100. *
  101. * @param client the connected SIOClient object.
  102. */
  103. virtual void onClose(SIOClient* client) = 0;
  104. /**
  105. * Pure virtual callback function, this function should be overridden by the subclass.
  106. *
  107. * 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.
  108. *
  109. * @param client the connected SIOClient object.
  110. * @param data the error message
  111. */
  112. virtual void onError(SIOClient* client, const std::string& data) = 0;
  113. /**
  114. * Fire event to script when the related SIOClient object receive the fire event signal.
  115. *
  116. * @param client the connected SIOClient object.
  117. * @param eventName the event's name.
  118. * @param data the event's data information.
  119. */
  120. 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()); };
  121. };
  122. /**
  123. * Static client creation method, similar to socketio.connect(uri) in JS.
  124. * @param uri the URI of the socket.io server.
  125. * @param delegate the delegate which want to receive events from the socket.io client.
  126. * @return SIOClient* an initialized SIOClient if connected successfully, otherwise nullptr.
  127. */
  128. static SIOClient* connect(const std::string& uri, SocketIO::SIODelegate& delegate);
  129. /**
  130. * Static client creation method, similar to socketio.connect(uri) in JS.
  131. * @param uri the URI of the socket.io server.
  132. * @param delegate the delegate which want to receive events from the socket.io client.
  133. * @param caFilePath The ca file path for wss connection
  134. * @return SIOClient* an initialized SIOClient if connected successfully, otherwise nullptr.
  135. */
  136. static SIOClient* connect(const std::string& uri, SocketIO::SIODelegate& delegate, const std::string& caFilePath);
  137. /**
  138. * Static client creation method, similar to socketio.connect(uri) in JS.
  139. * @param delegate the delegate which want to receive events from the socket.io client.
  140. * @param uri the URI of the socket.io server.
  141. * @return SIOClient* an initialized SIOClient if connected successfully, otherwise nullptr.
  142. */
  143. CC_DEPRECATED_ATTRIBUTE static SIOClient* connect(SocketIO::SIODelegate& delegate, const std::string& uri);
  144. private:
  145. SocketIO();
  146. virtual ~SocketIO();
  147. static SocketIO *_inst;
  148. cocos2d::Map<std::string, SIOClientImpl*> _sockets;
  149. SIOClientImpl* getSocket(const std::string& uri);
  150. void addSocket(const std::string& uri, SIOClientImpl* socket);
  151. void removeSocket(const std::string& uri);
  152. friend class SIOClientImpl;
  153. private:
  154. CC_DISALLOW_COPY_AND_ASSIGN(SocketIO)
  155. };
  156. //c++11 style callbacks entities will be created using CC_CALLBACK (which uses std::bind)
  157. typedef std::function<void(SIOClient*, const std::string&)> SIOEvent;
  158. //c++11 map to callbacks
  159. typedef std::unordered_map<std::string, SIOEvent> EventRegistry;
  160. /**
  161. * A single connection to a socket.io endpoint.
  162. *
  163. * @lua NA
  164. */
  165. class CC_DLL SIOClient
  166. : public cocos2d::Ref
  167. {
  168. private:
  169. friend class SocketIO; // Only SocketIO class could contruct a SIOClient instance.
  170. std::string _path, _tag;
  171. bool _connected;
  172. SIOClientImpl* _socket;
  173. SocketIO::SIODelegate* _delegate;
  174. EventRegistry _eventRegistry;
  175. void fireEvent(const std::string& eventName, const std::string& data);
  176. void onOpen();
  177. void onConnect();
  178. void socketClosed();
  179. friend class SIOClientImpl;
  180. /**
  181. * Constructor of SIOClient class.
  182. *
  183. * @param host the string that represent the host address.
  184. * @param port the int value represent the port number.
  185. * @param path the string that represent endpoint.
  186. * @param impl the SIOClientImpl object.
  187. * @param delegate the SIODelegate object.
  188. */
  189. SIOClient(const std::string& path, SIOClientImpl* impl, SocketIO::SIODelegate& delegate);
  190. /**
  191. * Destructor of SIOClient class.
  192. */
  193. virtual ~SIOClient();
  194. public:
  195. /**
  196. * Get the delegate for the client
  197. * @return the delegate object for the client
  198. */
  199. SocketIO::SIODelegate* getDelegate() { return _delegate; };
  200. /**
  201. * Disconnect from the endpoint, onClose will be called for the delegate when complete
  202. */
  203. void disconnect();
  204. /**
  205. * Send a message to the socket.io server.
  206. *
  207. * @param s message.
  208. */
  209. void send(const std::string& s);
  210. /**
  211. * Emit the eventname and the args to the endpoint that _path point to.
  212. * @param eventname
  213. * @param args
  214. */
  215. void emit(const std::string& eventname, const std::string& args);
  216. /**
  217. * Used to register a socket.io event callback.
  218. * Event argument should be passed using CC_CALLBACK2(&Base::function, this).
  219. * @param eventName the name of event.
  220. * @param e the callback function.
  221. */
  222. void on(const std::string& eventName, SIOEvent e);
  223. /**
  224. * Set tag of SIOClient.
  225. * The tag is used to distinguish the various SIOClient objects.
  226. * @param tag string object.
  227. */
  228. void setTag(const char* tag);
  229. /**
  230. * Get tag of SIOClient.
  231. * @return const char* the pointer point to the _tag.
  232. */
  233. const char* getTag()
  234. {
  235. return _tag.c_str();
  236. }
  237. };
  238. }
  239. NS_CC_END
  240. // end group
  241. /// @}
  242. #endif /* defined(__CC_JSB_SOCKETIO_H__) */