WebSocket.cpp 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  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/Log.h"
  25. #include "../Web/WebSocket.h"
  26. #ifdef EMSCRIPTEN
  27. #include "../DebugNew.h"
  28. // Add code to use an HTML5 style WebSocket here.
  29. #else
  30. #include "../Web/WebInternalConfig.h"
  31. #include <websocketpp/config/asio_no_tls_client.hpp>
  32. #include <websocketpp/client.hpp>
  33. #include <iostream>
  34. #include "../Core/Thread.h"
  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 work queue.
  46. asio::io_service service;
  47. /// The WebSocket external state.
  48. WebSocket &es;
  49. /// URL.
  50. String url;
  51. /// Error string. Empty if no error.
  52. String error;
  53. /// Connection state.
  54. WebSocketState state;
  55. /// WebSocket client.
  56. client c;
  57. /// WebSocket connection.
  58. client::connection_ptr con;
  59. WebSocketInternalState(WebSocket &es_)
  60. : es(es_)
  61. {
  62. }
  63. ~WebSocketInternalState()
  64. {
  65. }
  66. void OnOpen(websocketpp::connection_hdl hdl)
  67. {
  68. state = WS_OPEN;
  69. LOGDEBUG("WebSocket CONNECTED to: " + url);
  70. es.SendEvent("open");
  71. }
  72. void OnClose(websocketpp::connection_hdl hdl)
  73. {
  74. state = WS_CLOSED;
  75. LOGDEBUG("WebSocket DISCONNECTED from: " + url);
  76. es.SendEvent("close");
  77. }
  78. void OnFail(websocketpp::connection_hdl hdl)
  79. {
  80. state = WS_FAIL_TO_CONNECT;
  81. LOGDEBUG("WebSocket FAILED to connect to: " + url);
  82. es.SendEvent("fail_to_connect");
  83. }
  84. void OnMessage(websocketpp::connection_hdl hdl, message_ptr msg)
  85. {
  86. VariantMap eventData;
  87. const std::string &payload(msg->get_payload());
  88. eventData.Insert(MakePair(StringHash("type"), Variant(int(msg->get_opcode()))));
  89. switch (msg->get_opcode())
  90. {
  91. case websocketpp::frame::opcode::text:
  92. eventData.Insert(MakePair(StringHash("data"), Variant(String(payload.data(), payload.length()))));
  93. es.SendEvent("message", eventData);
  94. break;
  95. case websocketpp::frame::opcode::binary:
  96. eventData.Insert(MakePair(StringHash("data"), Variant(PODVector<unsigned char>((const unsigned char *)payload.data(), payload.length()))));
  97. es.SendEvent("message", eventData);
  98. break;
  99. default:
  100. eventData.Insert(MakePair(StringHash("data"), Variant(String(payload.data(), payload.length()))));
  101. LOGWARNING("Unsupported WebSocket message type: " + String(int(msg->get_opcode())));
  102. break;
  103. }
  104. }
  105. void MakeConnection()
  106. {
  107. websocketpp::lib::error_code ec;
  108. con = c.get_connection(url.CString(), ec);
  109. if (ec)
  110. {
  111. state = WS_INVALID;
  112. error = ec.message().c_str();
  113. LOGDEBUG("WebSocket error: " + error);
  114. es.SendEvent("invalid");
  115. return;
  116. }
  117. c.connect(con);
  118. }
  119. };
  120. WebSocket::WebSocket(Context* context, const String& url) :
  121. Object(context),
  122. is_(new WebSocketInternalState(*this))
  123. {
  124. is_->url = url.Trimmed();
  125. is_->state = WS_CONNECTING;
  126. is_->c.clear_access_channels(websocketpp::log::alevel::all);
  127. is_->c.clear_error_channels(websocketpp::log::elevel::all);
  128. }
  129. void WebSocket::setup(asio::io_service *service)
  130. {
  131. websocketpp::lib::error_code ec;
  132. is_->c.init_asio(service, ec);
  133. if (ec)
  134. {
  135. is_->state = WS_INVALID;
  136. is_->error = ec.message().c_str();
  137. LOGDEBUG("WebSocket error: " + is_->error);
  138. SendEvent("invalid");
  139. return;
  140. }
  141. is_->c.set_open_handler(bind(&WebSocketInternalState::OnOpen, is_, ::_1));
  142. is_->c.set_close_handler(bind(&WebSocketInternalState::OnClose, is_, ::_1));
  143. is_->c.set_fail_handler(bind(&WebSocketInternalState::OnFail, is_, ::_1));
  144. is_->c.set_message_handler(bind(&WebSocketInternalState::OnMessage, is_, ::_1, ::_2));
  145. LOGDEBUG("WebSocket request to URL " + is_->url);
  146. is_->MakeConnection();
  147. }
  148. WebSocket::~WebSocket()
  149. {
  150. delete is_;
  151. }
  152. const String& WebSocket::GetURL() const
  153. {
  154. return is_->url;
  155. }
  156. String WebSocket::GetError() const
  157. {
  158. return is_->error;
  159. }
  160. WebSocketState WebSocket::GetState() const
  161. {
  162. return is_->state;
  163. }
  164. void WebSocket::Send(String message)
  165. {
  166. is_->c.send(is_->con, message.CString(), message.Length(), websocketpp::frame::opcode::text);
  167. }
  168. void WebSocket::Close()
  169. {
  170. is_->state = WS_CLOSING;
  171. websocketpp::lib::error_code ec;
  172. LOGDEBUG("WebSocket atempting to close URL " + is_->url);
  173. is_->con->terminate(ec);
  174. }
  175. void WebSocket::OpenAgain()
  176. {
  177. is_->state = WS_CONNECTING;
  178. LOGDEBUG("WebSocket request (again) to URL " + is_->url);
  179. is_->MakeConnection();
  180. }
  181. }
  182. #endif