WebSocket.cpp 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. //
  2. // Copyright (c) 2014-2015, THUNDERBEAST GAMES LLC All rights reserved
  3. //
  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. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  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. //
  22. #include "../Precompiled.h"
  23. #include "../Core/Profiler.h"
  24. #include "../IO/BufferQueue.h"
  25. #include "../IO/Log.h"
  26. #include "../Web/WebSocket.h"
  27. #ifdef EMSCRIPTEN
  28. #include "../DebugNew.h"
  29. // Add code to use an HTML5 style WebSocket here.
  30. #else
  31. #include "../Web/WebInternalConfig.h"
  32. #include <websocketpp/config/asio_no_tls_client.hpp>
  33. #include <websocketpp/client.hpp>
  34. #include <iostream>
  35. #include "../DebugNew.h"
  36. typedef websocketpp::client<websocketpp::config::asio_client> client;
  37. typedef websocketpp::config::asio_client::message_type::ptr message_ptr;
  38. using websocketpp::lib::placeholders::_1;
  39. using websocketpp::lib::placeholders::_2;
  40. using websocketpp::lib::bind;
  41. namespace Atomic
  42. {
  43. struct WebSocketInternalState
  44. {
  45. /// The WebSocket external state.
  46. WebSocket *es;
  47. /// URL.
  48. String url;
  49. /// Error string. Empty if no error.
  50. String error;
  51. /// Connection state.
  52. WebSocketState state;
  53. /// WebSocket client.
  54. client c;
  55. /// WebSocket connection.
  56. client::connection_ptr con;
  57. WebSocketInternalState(WebSocket *es_)
  58. : es(es_)
  59. {
  60. LOGDEBUG("Create WebSocketInternalState");
  61. }
  62. ~WebSocketInternalState()
  63. {
  64. LOGDEBUG("Destroy WebSocketInternalState");
  65. }
  66. void OnOpen(websocketpp::connection_hdl hdl)
  67. {
  68. state = WS_OPEN;
  69. LOGDEBUG("WebSocket CONNECTED to: " + url);
  70. if (es)
  71. {
  72. es->SendEvent("open");
  73. }
  74. }
  75. void OnClose(websocketpp::connection_hdl hdl)
  76. {
  77. state = WS_CLOSED;
  78. LOGDEBUG("WebSocket DISCONNECTED from: " + url);
  79. if (es)
  80. {
  81. es->SendEvent("close");
  82. }
  83. }
  84. void OnFail(websocketpp::connection_hdl hdl)
  85. {
  86. state = WS_FAIL_TO_CONNECT;
  87. LOGDEBUG("WebSocket FAILED to connect to: " + url);
  88. if (es)
  89. {
  90. es->SendEvent("fail_to_connect");
  91. }
  92. }
  93. void OnMessage(websocketpp::connection_hdl hdl, message_ptr msg)
  94. {
  95. if (!es)
  96. {
  97. return;
  98. }
  99. VariantMap eventData;
  100. const std::string& payload(msg->get_payload());
  101. SharedPtr<BufferQueue> message(new BufferQueue(es->GetContext()));
  102. message->Write((const void*)payload.data(), (unsigned)payload.size());
  103. eventData.Insert(MakePair(StringHash("type"), Variant(int(msg->get_opcode()))));
  104. eventData.Insert(MakePair(StringHash("message"), Variant(message)));
  105. es->SendEvent("message", eventData);
  106. }
  107. void MakeConnection()
  108. {
  109. websocketpp::lib::error_code ec;
  110. con = c.get_connection(url.CString(), ec);
  111. if (ec)
  112. {
  113. state = WS_INVALID;
  114. error = ec.message().c_str();
  115. LOGDEBUG("WebSocket error: " + error);
  116. if (es)
  117. {
  118. es->SendEvent("invalid");
  119. }
  120. return;
  121. }
  122. c.connect(con);
  123. }
  124. };
  125. WebSocket::WebSocket(Context* context, const String& url) :
  126. Object(context),
  127. is_(new WebSocketInternalState(this))
  128. {
  129. is_->url = url.Trimmed();
  130. is_->state = WS_CONNECTING;
  131. is_->c.clear_access_channels(websocketpp::log::alevel::all);
  132. is_->c.clear_error_channels(websocketpp::log::elevel::all);
  133. }
  134. void WebSocket::setup(asio::io_service *service)
  135. {
  136. LOGDEBUG("Create WebSocket");
  137. websocketpp::lib::error_code ec;
  138. is_->c.init_asio(service, ec);
  139. if (ec)
  140. {
  141. is_->state = WS_INVALID;
  142. is_->error = ec.message().c_str();
  143. LOGDEBUG("WebSocket error: " + is_->error);
  144. SendEvent("invalid");
  145. return;
  146. }
  147. is_->c.set_open_handler(bind(&WebSocketInternalState::OnOpen, is_, ::_1));
  148. is_->c.set_close_handler(bind(&WebSocketInternalState::OnClose, is_, ::_1));
  149. is_->c.set_fail_handler(bind(&WebSocketInternalState::OnFail, is_, ::_1));
  150. is_->c.set_message_handler(bind(&WebSocketInternalState::OnMessage, is_, ::_1, ::_2));
  151. LOGDEBUG("WebSocket request to URL " + is_->url);
  152. is_->MakeConnection();
  153. }
  154. WebSocket::~WebSocket()
  155. {
  156. std::error_code ec;
  157. is_->es = nullptr;
  158. is_->con->terminate(ec);
  159. is_->c.set_open_handler(nullptr);
  160. is_->c.set_close_handler(nullptr);
  161. is_->c.set_fail_handler(nullptr);
  162. is_->c.set_message_handler(nullptr);
  163. is_->con.reset();
  164. is_.reset();
  165. LOGDEBUG("Destroy WebSocket");
  166. }
  167. const String& WebSocket::GetURL() const
  168. {
  169. return is_->url;
  170. }
  171. String WebSocket::GetError() const
  172. {
  173. return is_->error;
  174. }
  175. WebSocketState WebSocket::GetState() const
  176. {
  177. return is_->state;
  178. }
  179. void WebSocket::Send(const String& message)
  180. {
  181. is_->c.send(is_->con, message.CString(), message.Length(), websocketpp::frame::opcode::text);
  182. }
  183. void WebSocket::SendBinary(const PODVector<unsigned char>& message)
  184. {
  185. is_->c.send(is_->con, message.Buffer(), message.Size(), websocketpp::frame::opcode::binary);
  186. }
  187. void WebSocket::Close()
  188. {
  189. is_->state = WS_CLOSING;
  190. websocketpp::lib::error_code ec;
  191. LOGDEBUG("WebSocket atempting to close URL " + is_->url);
  192. is_->con->terminate(ec);
  193. }
  194. void WebSocket::OpenAgain()
  195. {
  196. is_->state = WS_CONNECTING;
  197. LOGDEBUG("WebSocket request (again) to URL " + is_->url);
  198. is_->MakeConnection();
  199. }
  200. }
  201. #endif