WSClient.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. //
  2. // Copyright (c) 2008-2020 the Urho3D project.
  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. #ifdef URHO3D_WEBSOCKETS
  23. #include "../../Core/WorkQueue.h"
  24. #include "../../IO/MemoryBuffer.h"
  25. #include "../../IO/Log.h"
  26. #include "../Network.h"
  27. #include "WSClient.h"
  28. #include "WSHandler.h"
  29. #include <string.h>
  30. #ifdef __EMSCRIPTEN__
  31. #include <emscripten.h>
  32. #include <emscripten/bind.h>
  33. enum lws_callback_reasons {
  34. LWS_CALLBACK_ESTABLISHED = 0,
  35. LWS_CALLBACK_CLIENT_CONNECTION_ERROR = 1,
  36. LWS_CALLBACK_CLIENT_ESTABLISHED = 3,
  37. LWS_CALLBACK_CLOSED = 4,
  38. LWS_CALLBACK_RECEIVE = 6,
  39. LWS_CALLBACK_CLIENT_RECEIVE = 8,
  40. LWS_CALLBACK_CLIENT_WRITEABLE = 10,
  41. LWS_CALLBACK_SERVER_WRITEABLE = 11,
  42. LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION = 20,
  43. LWS_CALLBACK_WSI_CREATE = 29,
  44. LWS_CALLBACK_WSI_DESTROY = 30,
  45. LWS_CALLBACK_CLIENT_CLOSED = 75
  46. };
  47. #else
  48. #include <libwebsockets.h>
  49. #endif
  50. static Urho3D::WSClient* WSClientInstance = nullptr;
  51. #if defined(WIN32)
  52. #define HAVE_STRUCT_TIMESPEC
  53. #if defined(pid_t)
  54. #undef pid_t
  55. #endif
  56. #endif
  57. #ifndef __EMSCRIPTEN__
  58. static struct lws *client_wsi;
  59. static lws_sorted_usec_list_t sul;
  60. static struct lws_context *wsContext;
  61. static lws_retry_bo_t retry{};
  62. /// Connect to server with retry functionality
  63. static void ConnectToServer(lws_sorted_usec_list_t *_sul)
  64. {
  65. struct lws_client_connect_info info;
  66. memset(&info, 0, sizeof(info));
  67. info.context = wsContext;
  68. info.port = WSClientInstance->GetPort();
  69. info.address = WSClientInstance->GetAddress().CString();
  70. info.path = "/";
  71. info.host = info.address;
  72. info.origin = info.address;
  73. info.protocol = WSClientInstance->GetServerProtocol().CString();
  74. info.alpn = "http/1.1";
  75. info.local_protocol_name = "ws_client";
  76. info.pwsi = &client_wsi;
  77. retry.secs_since_valid_ping = 3;
  78. retry.secs_since_valid_ping = 10;
  79. info.retry_and_idle_policy = &retry;
  80. if (!lws_client_connect_via_info(&info))
  81. lws_sul_schedule(wsContext, 0, _sul, ConnectToServer, 5 * LWS_USEC_PER_SEC);
  82. }
  83. #endif
  84. static int WSCallback(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len)
  85. {
  86. // URHO3D_LOGINFOF("Incoming client messsage reason %d", reason);
  87. switch (reason) {
  88. case LWS_CALLBACK_CLIENT_CONNECTION_ERROR:
  89. if (WSClientInstance) {
  90. WSClientInstance->SetState(Urho3D::WCS_CONNECTION_FAILED);
  91. }
  92. break;
  93. case LWS_CALLBACK_CLIENT_ESTABLISHED:
  94. if (WSClientInstance) {
  95. URHO3D_LOGINFOF("LWS_CALLBACK_CLIENT_ESTABLISHED");
  96. WSClientInstance->SetWSConnection(wsi);
  97. WSClientInstance->SetState(Urho3D::WCS_CONNECTED);
  98. }
  99. break;
  100. case LWS_CALLBACK_CLIENT_RECEIVE: {
  101. Urho3D::VectorBuffer b((unsigned char*)in, len);
  102. if (b.GetData()[0] == URHO3D_MESSAGE) {
  103. WSPacket packet(wsi, b);
  104. if (WSClientInstance) {
  105. WSClientInstance->AddIncomingPacket(packet);
  106. }
  107. } else {
  108. URHO3D_LOGINFOF("Received message that is not part of the engine %d", b.GetData()[0]);
  109. }
  110. #ifndef __EMSCRIPTEN__
  111. lws_callback_on_writable(wsi);
  112. #endif
  113. break;
  114. }
  115. case LWS_CALLBACK_CLIENT_WRITEABLE:
  116. if (WSClientInstance) {
  117. #ifndef __EMSCRIPTEN__
  118. WSClientInstance->SendOutMessages(wsi);
  119. #endif
  120. }
  121. break;
  122. case LWS_CALLBACK_CLIENT_CLOSED:
  123. #ifndef __EMSCRIPTEN__
  124. if (WSClientInstance) {
  125. WSClientInstance->Disconnect();
  126. }
  127. #endif
  128. URHO3D_LOGINFOF("LWS_CALLBACK_CLIENT_CLOSED");
  129. break;
  130. default:
  131. break;
  132. }
  133. return 0;
  134. }
  135. #ifdef __EMSCRIPTEN__
  136. static int WSHelper(intptr_t wsi, int reason, intptr_t user, intptr_t in, int len ) {
  137. return WSCallback(reinterpret_cast<struct lws *>(wsi), static_cast<enum lws_callback_reasons>(reason), reinterpret_cast<void*>(user), reinterpret_cast<void*>(in), (size_t)len);
  138. }
  139. using namespace emscripten;
  140. EMSCRIPTEN_BINDINGS(WSClient) {
  141. function("WSHelper", &WSHelper);
  142. }
  143. #endif
  144. #ifndef __EMSCRIPTEN__
  145. static const struct lws_protocols protocols[] = {
  146. {"ws_client", WSCallback,0,0,},
  147. { NULL, NULL, 0, 0 }
  148. };
  149. #endif
  150. using namespace Urho3D;
  151. static void RunService(const WorkItem* item, unsigned threadIndex) {
  152. #ifndef __EMSCRIPTEN__
  153. int result = lws_service(wsContext, 0);
  154. if (result < 0 && WSClientInstance) {
  155. WSClientInstance->Disconnect();
  156. }
  157. #endif
  158. }
  159. WSClient::WSClient(Context* context):
  160. Object(context),
  161. ws_(nullptr)
  162. {
  163. SetState(WCS_DISCONNECTED);
  164. WSClientInstance = this;
  165. #ifdef __EMSCRIPTEN__
  166. EM_ASM({
  167. var libwebsocket = {};
  168. libwebsocket.socket = false;
  169. libwebsocket.on_event = Module.WSHelper;
  170. libwebsocket.connect = function( url, protocol, user_data ) {
  171. try {
  172. var socket = new WebSocket(url,protocol);
  173. socket.binaryType = "arraybuffer";
  174. socket.user_data = user_data;
  175. socket.id = 1;
  176. socket.onopen = this.on_connect;
  177. socket.onmessage = this.on_message;
  178. socket.onclose = this.on_close;
  179. socket.onerror = this.on_error;
  180. socket.destroy = this.destroy;
  181. this.socket = socket;
  182. return socket;
  183. } catch(e) {
  184. console.log("Socket creation failed:" + e);
  185. return 0;
  186. }
  187. };
  188. libwebsocket.on_connect = function() {
  189. // var stack = stackSave();
  190. // filter protocol //
  191. // var ret = libwebsocket.on_event(this.id, 9, 0, allocate(intArrayFromString(this.protocol), 'i8', ALLOC_STACK), this.protocol.length);
  192. // if( !ret ) {
  193. // client established
  194. console.log('this.id, 3, 0, 0, 0', this.id, 3, 0, 0, 0);
  195. ret = libwebsocket.on_event(this.id, 3, 0, 0, 0);
  196. // }
  197. if( ret ) {
  198. this.close();
  199. }
  200. // stackRestore(stack);
  201. };
  202. libwebsocket.on_message = function(event) {
  203. var len = event.data.byteLength;
  204. var ptr = Module._malloc(len);
  205. const data = new Uint8Array(Module.HEAPU8.buffer, ptr, len);
  206. data.set(new Uint8Array(event.data));
  207. // client receive //
  208. if(libwebsocket.on_event(this.id, 8, 0, data.byteOffset, len)) {
  209. this.close();
  210. }
  211. Module._free(data.byteOffset);
  212. };
  213. libwebsocket.on_close = function() {
  214. // closed //
  215. libwebsocket.on_event(this.id, 4, 0, 0, 0);
  216. this.destroy();
  217. };
  218. libwebsocket.on_error = function() {
  219. // client connection error //
  220. libwebsocket.on_event(this.id, 1, 0, 0, 0);
  221. this.destroy();
  222. };
  223. libwebsocket.destroy = function() {
  224. libwebsocket.on_event(libwebsocket.socket.id, 75, 0, 0, 0);
  225. libwebsocket.socket = false;
  226. };
  227. Module.__libwebsocket = libwebsocket;
  228. });
  229. #endif
  230. }
  231. WSClient::~WSClient()
  232. {
  233. WSClientInstance = nullptr;
  234. }
  235. int WSClient::Connect(const String& address, unsigned short port)
  236. {
  237. address_ = address;
  238. port_ = port;
  239. serverProtocol_ = "ws-server";
  240. SetState(WCS_CONNECTING);
  241. SubscribeToEvent(E_WORKITEMCOMPLETED, URHO3D_HANDLER(WSClient, HandleWorkItemFinished));
  242. #ifndef __EMSCRIPTEN__
  243. struct lws_context_creation_info info;
  244. lws_set_log_level(LLL_USER | LLL_ERR | LLL_WARN | LLL_NOTICE, OutputWSLog);
  245. memset(&info, 0, sizeof info);
  246. info.port = CONTEXT_PORT_NO_LISTEN;
  247. info.protocols = protocols;
  248. wsContext = lws_create_context(&info);
  249. if (!wsContext) {
  250. URHO3D_LOGERROR("Failed to start Websocket client");
  251. return 1;
  252. }
  253. lws_sul_schedule(wsContext, 0, &sul, ConnectToServer, 50);
  254. #else
  255. EM_ASM({
  256. let address = UTF8ToString($0);
  257. let port = $1;
  258. let protocol = UTF8ToString($2);
  259. Module.__libwebsocket.connect(address);
  260. }, address_.CString(), port, serverProtocol_.CString());
  261. #endif
  262. return 0;
  263. }
  264. void WSClient::Update(float timestep)
  265. {
  266. if (currentState_ == WCS_CONNECTING && nextState_ == WCS_CONNECTED) {
  267. GetSubsystem<Network>()->OnServerConnected(GetWSConnection());
  268. URHO3D_LOGINFOF("WSclient OnServerConnected");
  269. }
  270. if (nextState_ == WCS_DISCONNECTED) {
  271. GetSubsystem<Network>()->OnServerDisconnected(GetWSConnection(), false);
  272. return;
  273. }
  274. if (nextState_ == WCS_CONNECTION_FAILED) {
  275. GetSubsystem<Network>()->OnServerDisconnected(GetWSConnection(), true);
  276. return;
  277. }
  278. #ifndef __EMSCRIPTEN__
  279. if (wsContext) {
  280. if (!serviceWorkItem_ && currentState_ != WCS_DISCONNECTED) {
  281. WorkQueue *workQueue = GetSubsystem<WorkQueue>();
  282. serviceWorkItem_ = workQueue->GetFreeItem();
  283. serviceWorkItem_->priority_ = M_MAX_INT;
  284. serviceWorkItem_->workFunction_ = RunService;
  285. serviceWorkItem_->aux_ = this;
  286. serviceWorkItem_->sendEvent_ = true;
  287. workQueue->AddWorkItem(serviceWorkItem_);
  288. }
  289. }
  290. #else
  291. // For web port we can send out messages immediatelly
  292. SendOutMessages(GetWSConnection());
  293. #endif
  294. while (GetNumIncomingPackets()) {
  295. auto packet = GetIncomingPacket();
  296. GetSubsystem<Network>()->HandleIncomingPacket(packet, false);
  297. RemoveIncomingPacket();
  298. }
  299. if (currentState_ != nextState_) {
  300. currentState_ = nextState_;
  301. }
  302. }
  303. void WSClient::Disconnect()
  304. {
  305. SetState(WCS_DISCONNECTED);
  306. #ifndef __EMSCRIPTEN__
  307. if (wsContext)
  308. {
  309. lws_context_destroy(wsContext);
  310. wsContext = nullptr;
  311. }
  312. #else
  313. EM_ASM({
  314. Module.__libwebsocket.destroy();
  315. });
  316. #endif
  317. }
  318. void WSClient::SetWSConnection(lws *ws)
  319. {
  320. ws_ = ws;
  321. }
  322. void WSClient::SetState(WSClientState state)
  323. {
  324. nextState_ = state;
  325. }
  326. void WSClient::HandleWorkItemFinished(StringHash eventType, VariantMap& eventData)
  327. {
  328. using namespace WorkItemCompleted;
  329. WorkItem *workItem = reinterpret_cast<WorkItem *>(eventData[P_ITEM].GetPtr());
  330. if (workItem->aux_ != this) {
  331. return;
  332. }
  333. if (workItem->workFunction_ == RunService) {
  334. serviceWorkItem_.Reset();
  335. }
  336. }
  337. void WSClient::SendOutMessages(lws *ws)
  338. {
  339. #ifdef __EMSCRIPTEN__
  340. if(GetNumOutgoingPackets(ws))
  341. {
  342. auto packet = GetOutgoingPacket(ws);
  343. if (packet)
  344. {
  345. int retval = EM_ASM_INT({
  346. var socket = Module.__libwebsocket.socket;
  347. if( ! socket ) {
  348. return -1;
  349. }
  350. // alloc a Uint8Array backed by the incoming data.
  351. var data_in = new Uint8Array(Module.HEAPU8.buffer, $0, $1);
  352. // allow the dest array
  353. var data = new Uint8Array($1);
  354. // set the dest from the src
  355. data.set(data_in);
  356. socket.send(data);
  357. return $1;
  358. }, packet->second_.GetData(), packet->second_.GetSize());
  359. if (retval < packet->second_.GetSize())
  360. {
  361. URHO3D_LOGERRORF("Failed to write to WS, bytes written = %d", retval);
  362. }
  363. else
  364. RemoveOutgoingPacket(ws);
  365. }
  366. }
  367. #else
  368. if(WSClientInstance->GetNumOutgoingPackets(ws)) {
  369. auto packet = WSClientInstance->GetOutgoingPacket(ws);
  370. if (packet) {
  371. unsigned char buf[LWS_PRE + packet->second_.GetSize()];
  372. memcpy(&buf[LWS_PRE], packet->second_.GetData(), packet->second_.GetSize());
  373. int retval = lws_write(ws, &buf[LWS_PRE], packet->second_.GetSize(), LWS_WRITE_BINARY);
  374. if (retval < packet->second_.GetSize()) {
  375. URHO3D_LOGERRORF("Failed to write to WS, bytes written = %d", retval);
  376. return;
  377. }
  378. WSClientInstance->RemoveOutgoingPacket(ws);
  379. }
  380. }
  381. lws_callback_on_writable(ws);
  382. #endif
  383. }
  384. #endif