WSClient.cpp 14 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. #ifdef __EMSCRIPTEN__
  118. if(WSClientInstance->GetNumOutgoingPackets(wsi))
  119. {
  120. auto packet = WSClientInstance->GetOutgoingPacket(wsi);
  121. if (packet)
  122. {
  123. int retval = EM_ASM_INT({
  124. var socket = Module.__libwebsocket.socket;
  125. if( ! socket ) {
  126. return -1;
  127. }
  128. // alloc a Uint8Array backed by the incoming data.
  129. var data_in = new Uint8Array(Module.HEAPU8.buffer, $1, $2 );
  130. // allow the dest array
  131. var data = new Uint8Array($2);
  132. // set the dest from the src
  133. data.set(data_in);
  134. socket.send(data);
  135. return $2;
  136. }, packet->second_.GetData(), packet->second_.GetSize());
  137. if (retval < packet->second_.GetSize()) {
  138. URHO3D_LOGERRORF("Failed to write to WS, bytes written = %d", retval);
  139. break;
  140. }
  141. WSClientInstance->RemoveOutgoingPacket(wsi);
  142. }
  143. }
  144. #else
  145. if(WSClientInstance->GetNumOutgoingPackets(wsi)) {
  146. auto packet = WSClientInstance->GetOutgoingPacket(wsi);
  147. if (packet) {
  148. unsigned char buf[LWS_PRE + packet->second_.GetSize()];
  149. memcpy(&buf[LWS_PRE], packet->second_.GetData(), packet->second_.GetSize());
  150. int retval = lws_write(wsi, &buf[LWS_PRE], packet->second_.GetSize(), LWS_WRITE_BINARY);
  151. if (retval < packet->second_.GetSize()) {
  152. URHO3D_LOGERRORF("Failed to write to WS, bytes written = %d", retval);
  153. break;
  154. }
  155. WSClientInstance->RemoveOutgoingPacket(wsi);
  156. }
  157. }
  158. lws_callback_on_writable(wsi);
  159. #endif
  160. }
  161. break;
  162. case LWS_CALLBACK_CLIENT_CLOSED:
  163. if (WSClientInstance) {
  164. WSClientInstance->Disconnect();
  165. }
  166. URHO3D_LOGINFOF("LWS_CALLBACK_CLIENT_CLOSED");
  167. break;
  168. default:
  169. break;
  170. }
  171. return 0;
  172. }
  173. #ifdef __EMSCRIPTEN__
  174. static int WSHelper(intptr_t wsi, int reason, intptr_t user, intptr_t in, int len ) {
  175. 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);
  176. }
  177. using namespace emscripten;
  178. EMSCRIPTEN_BINDINGS(WSClient) {
  179. function("WSHelper", &WSHelper);
  180. }
  181. #endif
  182. #ifndef __EMSCRIPTEN__
  183. static const struct lws_protocols protocols[] = {
  184. {"ws_client", WSCallback,0,0,},
  185. { NULL, NULL, 0, 0 }
  186. };
  187. #endif
  188. using namespace Urho3D;
  189. static void RunService(const WorkItem* item, unsigned threadIndex) {
  190. #ifndef __EMSCRIPTEN__
  191. int result = lws_service(wsContext, 0);
  192. if (result < 0 && WSClientInstance) {
  193. WSClientInstance->Disconnect();
  194. }
  195. #endif
  196. }
  197. WSClient::WSClient(Context* context):
  198. Object(context),
  199. ws_(nullptr)
  200. {
  201. SetState(WCS_DISCONNECTED);
  202. WSClientInstance = this;
  203. #ifdef __EMSCRIPTEN__
  204. EM_ASM({
  205. var libwebsocket = {};
  206. libwebsocket.socket = false;
  207. libwebsocket.on_event = Module.WSHelper;
  208. libwebsocket.connect = function( url, protocol, user_data ) {
  209. try {
  210. var socket = new WebSocket(url,protocol);
  211. socket.binaryType = "arraybuffer";
  212. socket.user_data = user_data;
  213. socket.id = 1;
  214. socket.onopen = this.on_connect;
  215. socket.onmessage = this.on_message;
  216. socket.onclose = this.on_close;
  217. socket.onerror = this.on_error;
  218. socket.destroy = this.destroy;
  219. this.socket = socket;
  220. return socket;
  221. } catch(e) {
  222. console.log("Socket creation failed:" + e);
  223. return 0;
  224. }
  225. };
  226. libwebsocket.on_connect = function() {
  227. // var stack = stackSave();
  228. // filter protocol //
  229. // var ret = libwebsocket.on_event(this.id, 9, 0, allocate(intArrayFromString(this.protocol), 'i8', ALLOC_STACK), this.protocol.length);
  230. // if( !ret ) {
  231. // client established
  232. console.log('this.id, 3, 0, 0, 0', this.id, 3, 0, 0, 0);
  233. ret = libwebsocket.on_event(this.id, 3, 0, 0, 0);
  234. // }
  235. if( ret ) {
  236. this.close();
  237. }
  238. // stackRestore(stack);
  239. };
  240. libwebsocket.on_message = function(event) {
  241. console.log('on_message', event);
  242. // const nDataBytes = data.byteLength;
  243. // const dataPtr = Module._malloc(nDataBytes);
  244. // const dataHeap = new Uint8Array(Module.HEAPU8.buffer, dataPtr, nDataBytes);
  245. // dataHeap.set(new Uint8Array(data));
  246. // if (Module.JSResponse) {
  247. // Module.JSResponse(httpRequestHandlerPtr, dataHeap.byteOffset, nDataBytes);
  248. // } else {
  249. // console.error('Module.JSResponse() method doesn\'t exist');
  250. // }
  251. // Module._free(dataHeap.byteOffset);
  252. // var stack = stackSave();
  253. var len = event.data.byteLength;
  254. var ptr = Module._malloc(len);
  255. const data = new Uint8Array(Module.HEAPU8.buffer, dataPtr, nDataBytes);
  256. data.set(new Uint8Array(event.data));
  257. // client receive //
  258. if(libwebsocket.on_event(this.id, 8, 0, data.byteOffset, len)) {
  259. this.close();
  260. }
  261. Module._free(data.byteOffset);
  262. // stackRestore(stack);
  263. };
  264. libwebsocket.on_close = function() {
  265. // closed //
  266. libwebsocket.on_event(this.id, 4, 0, 0, 0);
  267. this.destroy();
  268. };
  269. libwebsocket.on_error = function() {
  270. // client connection error //
  271. libwebsocket.on_event(this.id, 1, 0, 0, 0);
  272. this.destroy();
  273. };
  274. libwebsocket.destroy = function() {
  275. libwebsocket.socket = false;
  276. libwebsocket.on_event(this.id, 75, 0, 0, 0);
  277. };
  278. Module.__libwebsocket = libwebsocket;
  279. });
  280. #endif
  281. }
  282. WSClient::~WSClient()
  283. {
  284. WSClientInstance = nullptr;
  285. }
  286. int WSClient::Connect(const String& address, unsigned short port)
  287. {
  288. address_ = address;
  289. port_ = port;
  290. serverProtocol_ = "ws-server";
  291. SetState(WCS_CONNECTING);
  292. SubscribeToEvent(E_WORKITEMCOMPLETED, URHO3D_HANDLER(WSClient, HandleWorkItemFinished));
  293. #ifndef __EMSCRIPTEN__
  294. struct lws_context_creation_info info;
  295. lws_set_log_level(LLL_USER | LLL_ERR | LLL_WARN | LLL_NOTICE, OutputWSLog);
  296. memset(&info, 0, sizeof info);
  297. info.port = CONTEXT_PORT_NO_LISTEN;
  298. info.protocols = protocols;
  299. wsContext = lws_create_context(&info);
  300. if (!wsContext) {
  301. URHO3D_LOGERROR("Failed to start Websocket client");
  302. return 1;
  303. }
  304. lws_sul_schedule(wsContext, 0, &sul, ConnectToServer, 50);
  305. #else
  306. EM_ASM({
  307. let address = UTF8ToString($0);
  308. let port = $1;
  309. let protocol = UTF8ToString($2);
  310. Module.__libwebsocket.connect(address);
  311. }, address_.CString(), port, serverProtocol_.CString());
  312. #endif
  313. return 0;
  314. }
  315. void WSClient::Update(float timestep)
  316. {
  317. if (currentState_ == WCS_CONNECTING && nextState_ == WCS_CONNECTED) {
  318. GetSubsystem<Network>()->OnServerConnected(GetWSConnection());
  319. URHO3D_LOGINFOF("WSclient OnServerConnected");
  320. }
  321. if (nextState_ == WCS_DISCONNECTED) {
  322. GetSubsystem<Network>()->OnServerDisconnected(GetWSConnection(), false);
  323. return;
  324. }
  325. if (nextState_ == WCS_CONNECTION_FAILED) {
  326. GetSubsystem<Network>()->OnServerDisconnected(GetWSConnection(), true);
  327. return;
  328. }
  329. #ifndef __EMSCRIPTEN__
  330. if (wsContext) {
  331. if (!serviceWorkItem_ && currentState_ != WCS_DISCONNECTED) {
  332. WorkQueue *workQueue = GetSubsystem<WorkQueue>();
  333. serviceWorkItem_ = workQueue->GetFreeItem();
  334. serviceWorkItem_->priority_ = M_MAX_INT;
  335. serviceWorkItem_->workFunction_ = RunService;
  336. serviceWorkItem_->aux_ = this;
  337. serviceWorkItem_->sendEvent_ = true;
  338. workQueue->AddWorkItem(serviceWorkItem_);
  339. }
  340. }
  341. #endif
  342. while (GetNumIncomingPackets()) {
  343. auto packet = GetIncomingPacket();
  344. GetSubsystem<Network>()->HandleIncomingPacket(packet, false);
  345. RemoveIncomingPacket();
  346. }
  347. if (currentState_ != nextState_) {
  348. currentState_ = nextState_;
  349. }
  350. }
  351. void WSClient::Disconnect()
  352. {
  353. SetState(WCS_DISCONNECTED);
  354. #ifndef __EMSCRIPTEN__
  355. if (wsContext)
  356. {
  357. lws_context_destroy(wsContext);
  358. wsContext = nullptr;
  359. }
  360. #else
  361. EM_ASM({
  362. Module.__libwebsocket.destroy();
  363. });
  364. #endif
  365. }
  366. void WSClient::SetWSConnection(lws *ws)
  367. {
  368. ws_ = ws;
  369. }
  370. void WSClient::SetState(WSClientState state)
  371. {
  372. nextState_ = state;
  373. }
  374. void WSClient::HandleWorkItemFinished(StringHash eventType, VariantMap& eventData)
  375. {
  376. using namespace WorkItemCompleted;
  377. WorkItem *workItem = reinterpret_cast<WorkItem *>(eventData[P_ITEM].GetPtr());
  378. if (workItem->aux_ != this) {
  379. return;
  380. }
  381. if (workItem->workFunction_ == RunService) {
  382. serviceWorkItem_.Reset();
  383. }
  384. }
  385. #endif