WebSocket-apple.mm 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. /****************************************************************************
  2. Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
  3. http://www.cocos.com
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated engine source code (the "Software"), a limited,
  6. worldwide, royalty-free, non-assignable, revocable and non-exclusive license
  7. to use Cocos Creator solely to develop games on your target platforms. You shall
  8. not use Cocos Creator software for developing other software or tools that's
  9. used for developing games. You are not granted to publish, distribute,
  10. sublicense, and/or sell copies of Cocos Creator.
  11. The software or tools in this License Agreement are licensed, not sold.
  12. Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
  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. ****************************************************************************/
  21. #include "network/WebSocket.h"
  22. #include "base/CCData.h"
  23. #import "SocketRocket/SocketRocket.h"
  24. #if !__has_feature(objc_arc)
  25. #error WebSocket must be compiled with ARC enabled
  26. #endif
  27. static std::vector<cocos2d::network::WebSocket*>* __websocketInstances = nullptr;
  28. @interface WebSocketImpl : NSObject<SRWebSocketDelegate>
  29. {
  30. }
  31. @end
  32. //
  33. @implementation WebSocketImpl
  34. {
  35. SRWebSocket* _ws;
  36. cocos2d::network::WebSocket* _ccws;
  37. cocos2d::network::WebSocket::Delegate* _delegate;
  38. std::string _url;
  39. std::string _selectedProtocol;
  40. bool _isDestroyed;
  41. }
  42. -(id) initWithURL:(const std::string&) url protocols:(NSArray<NSString *> *)protocols allowsUntrustedSSLCertificates:(BOOL)allowsUntrustedSSLCertificates ws:(cocos2d::network::WebSocket*) ccws delegate:(const cocos2d::network::WebSocket::Delegate&) delegate
  43. {
  44. if (self = [super init])
  45. {
  46. _ccws = ccws;
  47. _delegate = const_cast<cocos2d::network::WebSocket::Delegate*>(&delegate);
  48. _url = url;
  49. NSURL* nsUrl = [[NSURL alloc] initWithString:[[NSString alloc] initWithUTF8String:_url.c_str()]];
  50. _ws = [[SRWebSocket alloc] initWithURL:nsUrl protocols:protocols allowsUntrustedSSLCertificates:allowsUntrustedSSLCertificates];
  51. _ws.delegate = self;
  52. [_ws open];
  53. _isDestroyed = false;
  54. }
  55. return self;
  56. }
  57. -(void) dealloc
  58. {
  59. // NSLog(@"WebSocketImpl-apple dealloc: %p, SRWebSocket ref: %ld", self, CFGetRetainCount((__bridge CFTypeRef)_ws));
  60. }
  61. -(void) sendString:(NSString*) message
  62. {
  63. [_ws sendString:message error:nil];
  64. }
  65. -(void) sendData:(NSData*) data
  66. {
  67. [_ws sendData:data error:nil];
  68. }
  69. -(void) close
  70. {
  71. _isDestroyed = true;
  72. _ccws->retain();
  73. _delegate->onClose(_ccws);
  74. [_ws close];
  75. _ccws->release();
  76. }
  77. -(void) closeAsync
  78. {
  79. [_ws close];
  80. }
  81. -(cocos2d::network::WebSocket::State) getReadyState
  82. {
  83. cocos2d::network::WebSocket::State ret;
  84. SRReadyState state = _ws.readyState;
  85. switch (state) {
  86. case SR_OPEN:
  87. ret = cocos2d::network::WebSocket::State::OPEN;
  88. break;
  89. case SR_CONNECTING:
  90. ret = cocos2d::network::WebSocket::State::CONNECTING;
  91. break;
  92. case SR_CLOSING:
  93. ret = cocos2d::network::WebSocket::State::CLOSING;
  94. break;
  95. default:
  96. ret = cocos2d::network::WebSocket::State::CLOSED;
  97. break;
  98. }
  99. return ret;
  100. }
  101. -(const std::string&) getUrl
  102. {
  103. return _url;
  104. }
  105. -(const std::string&) getProtocol
  106. {
  107. return _selectedProtocol;
  108. }
  109. -(cocos2d::network::WebSocket::Delegate*) getDelegate
  110. {
  111. return (cocos2d::network::WebSocket::Delegate*)_delegate;
  112. }
  113. // Delegate methods
  114. -(void)webSocketDidOpen:(SRWebSocket *)webSocket;
  115. {
  116. if (!_isDestroyed)
  117. {
  118. // NSLog(@"Websocket Connected");
  119. if (webSocket.protocol != nil)
  120. _selectedProtocol = [webSocket.protocol UTF8String];
  121. _delegate->onOpen(_ccws);
  122. }
  123. else
  124. {
  125. NSLog(@"WebSocketImpl webSocketDidOpen was destroyed!");
  126. }
  127. }
  128. - (void)webSocket:(SRWebSocket *)webSocket didFailWithError:(NSError *)error;
  129. {
  130. if (!_isDestroyed)
  131. {
  132. NSLog(@":( Websocket Failed With Error %@", error);
  133. _delegate->onError(_ccws, cocos2d::network::WebSocket::ErrorCode::UNKNOWN);
  134. [self webSocket:webSocket didCloseWithCode:0 reason:@"onerror" wasClean:YES];
  135. }
  136. else
  137. {
  138. NSLog(@"WebSocketImpl didFailWithError was destroyed!");
  139. }
  140. }
  141. - (void)webSocket:(SRWebSocket *)webSocket didReceiveMessageWithString:(nonnull NSString *)string
  142. {
  143. if (!_isDestroyed)
  144. {
  145. std::string message = [string UTF8String];
  146. cocos2d::network::WebSocket::Data data;
  147. data.bytes = (char*)message.c_str();
  148. data.len = message.length() + 1;
  149. data.isBinary = false;
  150. data.issued = 0;
  151. data.ext = nullptr;
  152. _delegate->onMessage(_ccws, data);
  153. }
  154. else
  155. {
  156. NSLog(@"WebSocketImpl didReceiveMessageWithString was destroyed!");
  157. }
  158. }
  159. - (void)webSocket:(SRWebSocket *)webSocket didReceiveMessageWithData:(NSData *)nsData
  160. {
  161. if (!_isDestroyed)
  162. {
  163. cocos2d::network::WebSocket::Data data;
  164. data.bytes = (char*)nsData.bytes;
  165. data.len = nsData.length;
  166. data.isBinary = true;
  167. data.issued = 0;
  168. data.ext = nullptr;
  169. _delegate->onMessage(_ccws, data);
  170. }
  171. else
  172. {
  173. NSLog(@"WebSocketImpl didReceiveMessageWithData was destroyed!");
  174. }
  175. }
  176. - (void)webSocket:(SRWebSocket *)webSocket didCloseWithCode:(NSInteger)code reason:(NSString *)reason wasClean:(BOOL)wasClean
  177. {
  178. if (!_isDestroyed)
  179. _delegate->onClose(_ccws);
  180. else
  181. NSLog(@"WebSocketImpl didCloseWithCode was destroyed!");
  182. }
  183. @end
  184. NS_CC_BEGIN
  185. namespace network {
  186. void WebSocket::closeAllConnections()
  187. {
  188. if (__websocketInstances != nullptr)
  189. {
  190. ssize_t count = __websocketInstances->size();
  191. for (ssize_t i = count-1; i >=0 ; i--)
  192. {
  193. WebSocket* instance = __websocketInstances->at(i);
  194. instance->close();
  195. }
  196. __websocketInstances->clear();
  197. delete __websocketInstances;
  198. __websocketInstances = nullptr;
  199. }
  200. }
  201. WebSocket::WebSocket()
  202. : _impl(nil)
  203. {
  204. if (__websocketInstances == nullptr)
  205. {
  206. __websocketInstances = new (std::nothrow) std::vector<WebSocket*>();
  207. }
  208. __websocketInstances->push_back(this);
  209. }
  210. WebSocket::~WebSocket()
  211. {
  212. // NSLog(@"In the destructor of WebSocket-apple (%p).", this);
  213. if (__websocketInstances != nullptr)
  214. {
  215. auto iter = std::find(__websocketInstances->begin(), __websocketInstances->end(), this);
  216. if (iter != __websocketInstances->end())
  217. {
  218. __websocketInstances->erase(iter);
  219. }
  220. else
  221. {
  222. NSLog(@"ERROR: WebSocket instance wasn't added to the container which saves websocket instances!");
  223. }
  224. }
  225. }
  226. bool WebSocket::init(const Delegate& delegate,
  227. const std::string& url,
  228. const std::vector<std::string>* protocols/* = nullptr*/,
  229. const std::string& caFilePath/* = ""*/)
  230. {
  231. if (url.empty())
  232. return false;
  233. NSMutableArray* nsProtocols = [[NSMutableArray alloc] init];
  234. if (protocols != nullptr)
  235. {
  236. for (const auto& protocol : *protocols)
  237. {
  238. [nsProtocols addObject:[[NSString alloc] initWithUTF8String:protocol.c_str()]];
  239. }
  240. }
  241. _impl = [[WebSocketImpl alloc] initWithURL: url protocols:nsProtocols allowsUntrustedSSLCertificates:NO ws: this delegate:delegate];
  242. return _impl != nil;
  243. }
  244. void WebSocket::send(const std::string& message)
  245. {
  246. if ([_impl getReadyState] == State::OPEN)
  247. {
  248. NSString* str = [[NSString alloc] initWithUTF8String:message.c_str()];
  249. [_impl sendString:str];
  250. }
  251. else
  252. {
  253. NSLog(@"Couldn't send message since websocket wasn't opened!");
  254. }
  255. }
  256. void WebSocket::send(const unsigned char* binaryMsg, unsigned int len)
  257. {
  258. if ([_impl getReadyState] == State::OPEN)
  259. {
  260. NSData* data = [[NSData alloc] initWithBytes:binaryMsg length:(NSUInteger)len];
  261. [_impl sendData:data];
  262. }
  263. else
  264. {
  265. NSLog(@"Couldn't send message since websocket wasn't opened!");
  266. }
  267. }
  268. void WebSocket::close()
  269. {
  270. if ([_impl getReadyState] == State::CLOSING || [_impl getReadyState] == State::CLOSED)
  271. {
  272. NSLog(@"WebSocket (%p) was closed, no need to close it again!", this);
  273. return;
  274. }
  275. [_impl close];
  276. }
  277. void WebSocket::closeAsync()
  278. {
  279. if ([_impl getReadyState] == State::CLOSING || [_impl getReadyState] == State::CLOSED)
  280. {
  281. NSLog(@"WebSocket (%p) was closed, no need to close it again!", this);
  282. return;
  283. }
  284. [_impl closeAsync];
  285. }
  286. void WebSocket::closeAsync(int code, const std::string &reason)
  287. {
  288. //lws_close_reason() replacement required
  289. closeAsync();
  290. }
  291. std::string WebSocket::getExtensions() const
  292. {
  293. //TODO websocket extensions
  294. return "";
  295. }
  296. size_t WebSocket::getBufferedAmount() const
  297. {
  298. //TODO pending send bytes
  299. return 0;
  300. }
  301. WebSocket::State WebSocket::getReadyState() const
  302. {
  303. return [_impl getReadyState];
  304. }
  305. const std::string& WebSocket::getUrl() const
  306. {
  307. return [_impl getUrl];
  308. }
  309. const std::string& WebSocket::getProtocol() const
  310. {
  311. return [_impl getProtocol];
  312. }
  313. WebSocket::Delegate* WebSocket::getDelegate() const
  314. {
  315. return [_impl getDelegate];
  316. }
  317. } // namespace network {
  318. NS_CC_END