emws_client.cpp 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  1. /*************************************************************************/
  2. /* emws_client.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /*************************************************************************/
  30. #ifdef JAVASCRIPT_ENABLED
  31. #include "emws_client.h"
  32. #include "core/io/ip.h"
  33. #include "core/project_settings.h"
  34. #include "emscripten.h"
  35. extern "C" {
  36. EMSCRIPTEN_KEEPALIVE void _esws_on_connect(void *obj, char *proto) {
  37. EMWSClient *client = static_cast<EMWSClient *>(obj);
  38. client->_is_connecting = false;
  39. client->_on_connect(String(proto));
  40. }
  41. EMSCRIPTEN_KEEPALIVE void _esws_on_message(void *obj, uint8_t *p_data, int p_data_size, int p_is_string) {
  42. EMWSClient *client = static_cast<EMWSClient *>(obj);
  43. Error err = static_cast<EMWSPeer *>(*client->get_peer(1))->read_msg(p_data, p_data_size, p_is_string == 1);
  44. if (err == OK)
  45. client->_on_peer_packet();
  46. }
  47. EMSCRIPTEN_KEEPALIVE void _esws_on_error(void *obj) {
  48. EMWSClient *client = static_cast<EMWSClient *>(obj);
  49. client->_is_connecting = false;
  50. client->_on_error();
  51. }
  52. EMSCRIPTEN_KEEPALIVE void _esws_on_close(void *obj, int code, char *reason, int was_clean) {
  53. EMWSClient *client = static_cast<EMWSClient *>(obj);
  54. client->_on_close_request(code, String(reason));
  55. client->_is_connecting = false;
  56. client->_on_disconnect(was_clean != 0);
  57. }
  58. }
  59. Error EMWSClient::connect_to_host(String p_host, String p_path, uint16_t p_port, bool p_ssl, PoolVector<String> p_protocols) {
  60. String proto_string = p_protocols.join(",");
  61. String str = "ws://";
  62. if (p_ssl)
  63. str = "wss://";
  64. str += p_host + ":" + itos(p_port) + p_path;
  65. _is_connecting = true;
  66. /* clang-format off */
  67. int peer_sock = EM_ASM_INT({
  68. var proto_str = UTF8ToString($2);
  69. var socket = null;
  70. if (proto_str) {
  71. socket = new WebSocket(UTF8ToString($1), proto_str.split(","));
  72. } else {
  73. socket = new WebSocket(UTF8ToString($1));
  74. }
  75. var c_ptr = Module.IDHandler.get($0);
  76. socket.binaryType = "arraybuffer";
  77. // Connection opened
  78. socket.addEventListener("open", function (event) {
  79. if (!Module.IDHandler.has($0))
  80. return; // Godot Object is gone!
  81. ccall("_esws_on_connect",
  82. "void",
  83. ["number", "string"],
  84. [c_ptr, socket.protocol]
  85. );
  86. });
  87. // Listen for messages
  88. socket.addEventListener("message", function (event) {
  89. if (!Module.IDHandler.has($0))
  90. return; // Godot Object is gone!
  91. var buffer;
  92. var is_string = 0;
  93. if (event.data instanceof ArrayBuffer) {
  94. buffer = new Uint8Array(event.data);
  95. } else if (event.data instanceof Blob) {
  96. alert("Blob type not supported");
  97. return;
  98. } else if (typeof event.data === "string") {
  99. is_string = 1;
  100. var enc = new TextEncoder("utf-8");
  101. buffer = new Uint8Array(enc.encode(event.data));
  102. } else {
  103. alert("Unknown message type");
  104. return;
  105. }
  106. var len = buffer.length*buffer.BYTES_PER_ELEMENT;
  107. var out = Module._malloc(len);
  108. Module.HEAPU8.set(buffer, out);
  109. ccall("_esws_on_message",
  110. "void",
  111. ["number", "number", "number", "number"],
  112. [c_ptr, out, len, is_string]
  113. );
  114. Module._free(out);
  115. });
  116. socket.addEventListener("error", function (event) {
  117. if (!Module.IDHandler.has($0))
  118. return; // Godot Object is gone!
  119. ccall("_esws_on_error",
  120. "void",
  121. ["number"],
  122. [c_ptr]
  123. );
  124. });
  125. socket.addEventListener("close", function (event) {
  126. if (!Module.IDHandler.has($0))
  127. return; // Godot Object is gone!
  128. var was_clean = 0;
  129. if (event.wasClean)
  130. was_clean = 1;
  131. ccall("_esws_on_close",
  132. "void",
  133. ["number", "number", "string", "number"],
  134. [c_ptr, event.code, event.reason, was_clean]
  135. );
  136. });
  137. return Module.IDHandler.add(socket);
  138. }, _js_id, str.utf8().get_data(), proto_string.utf8().get_data());
  139. /* clang-format on */
  140. static_cast<Ref<EMWSPeer> >(_peer)->set_sock(peer_sock, _in_buf_size, _in_pkt_size);
  141. return OK;
  142. };
  143. void EMWSClient::poll() {
  144. }
  145. Ref<WebSocketPeer> EMWSClient::get_peer(int p_peer_id) const {
  146. return _peer;
  147. }
  148. NetworkedMultiplayerPeer::ConnectionStatus EMWSClient::get_connection_status() const {
  149. if (_peer->is_connected_to_host())
  150. return CONNECTION_CONNECTED;
  151. if (_is_connecting)
  152. return CONNECTION_CONNECTING;
  153. return CONNECTION_DISCONNECTED;
  154. };
  155. void EMWSClient::disconnect_from_host(int p_code, String p_reason) {
  156. _peer->close(p_code, p_reason);
  157. };
  158. IP_Address EMWSClient::get_connected_host() const {
  159. return IP_Address();
  160. };
  161. uint16_t EMWSClient::get_connected_port() const {
  162. return 1025;
  163. };
  164. int EMWSClient::get_max_packet_size() const {
  165. return (1 << _in_buf_size) - PROTO_SIZE;
  166. }
  167. EMWSClient::EMWSClient() {
  168. _in_buf_size = nearest_shift((int)GLOBAL_GET(WSC_IN_BUF) - 1) + 10;
  169. _in_pkt_size = nearest_shift((int)GLOBAL_GET(WSC_IN_PKT) - 1);
  170. _is_connecting = false;
  171. _peer = Ref<EMWSPeer>(memnew(EMWSPeer));
  172. /* clang-format off */
  173. _js_id = EM_ASM_INT({
  174. return Module.IDHandler.add($0);
  175. }, this);
  176. /* clang-format on */
  177. };
  178. EMWSClient::~EMWSClient() {
  179. disconnect_from_host();
  180. _peer = Ref<EMWSPeer>();
  181. /* clang-format off */
  182. EM_ASM({
  183. Module.IDHandler.remove($0);
  184. }, _js_id);
  185. /* clang-format on */
  186. };
  187. #endif // JAVASCRIPT_ENABLED