emws_client.cpp 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. /*************************************************************************/
  2. /* emws_client.cpp */
  3. /*************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /*************************************************************************/
  8. /* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur. */
  9. /* Copyright (c) 2014-2020 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, const Vector<String> p_protocols, const Vector<String> p_custom_headers) {
  60. String proto_string;
  61. for (int i = 0; i < p_protocols.size(); i++) {
  62. if (i != 0)
  63. proto_string += ",";
  64. proto_string += p_protocols[i];
  65. }
  66. String str = "ws://";
  67. if (p_custom_headers.size()) {
  68. WARN_PRINT_ONCE("Custom headers are not supported in in HTML5 platform.");
  69. }
  70. if (p_ssl) {
  71. str = "wss://";
  72. if (ssl_cert.is_valid()) {
  73. WARN_PRINT_ONCE("Custom SSL certificate is not supported in HTML5 platform.");
  74. }
  75. }
  76. str += p_host + ":" + itos(p_port) + p_path;
  77. _is_connecting = true;
  78. /* clang-format off */
  79. int peer_sock = EM_ASM_INT({
  80. var proto_str = UTF8ToString($2);
  81. var socket = null;
  82. try {
  83. if (proto_str) {
  84. socket = new WebSocket(UTF8ToString($1), proto_str.split(","));
  85. } else {
  86. socket = new WebSocket(UTF8ToString($1));
  87. }
  88. } catch (e) {
  89. return -1;
  90. }
  91. var c_ptr = Module.IDHandler.get($0);
  92. socket.binaryType = "arraybuffer";
  93. // Connection opened
  94. socket.addEventListener("open", function (event) {
  95. if (!Module.IDHandler.has($0))
  96. return; // Godot Object is gone!
  97. ccall("_esws_on_connect",
  98. "void",
  99. ["number", "string"],
  100. [c_ptr, socket.protocol]
  101. );
  102. });
  103. // Listen for messages
  104. socket.addEventListener("message", function (event) {
  105. if (!Module.IDHandler.has($0))
  106. return; // Godot Object is gone!
  107. var buffer;
  108. var is_string = 0;
  109. if (event.data instanceof ArrayBuffer) {
  110. buffer = new Uint8Array(event.data);
  111. } else if (event.data instanceof Blob) {
  112. alert("Blob type not supported");
  113. return;
  114. } else if (typeof event.data === "string") {
  115. is_string = 1;
  116. var enc = new TextEncoder("utf-8");
  117. buffer = new Uint8Array(enc.encode(event.data));
  118. } else {
  119. alert("Unknown message type");
  120. return;
  121. }
  122. var len = buffer.length*buffer.BYTES_PER_ELEMENT;
  123. var out = _malloc(len);
  124. HEAPU8.set(buffer, out);
  125. ccall("_esws_on_message",
  126. "void",
  127. ["number", "number", "number", "number"],
  128. [c_ptr, out, len, is_string]
  129. );
  130. _free(out);
  131. });
  132. socket.addEventListener("error", function (event) {
  133. if (!Module.IDHandler.has($0))
  134. return; // Godot Object is gone!
  135. ccall("_esws_on_error",
  136. "void",
  137. ["number"],
  138. [c_ptr]
  139. );
  140. });
  141. socket.addEventListener("close", function (event) {
  142. if (!Module.IDHandler.has($0))
  143. return; // Godot Object is gone!
  144. var was_clean = 0;
  145. if (event.wasClean)
  146. was_clean = 1;
  147. ccall("_esws_on_close",
  148. "void",
  149. ["number", "number", "string", "number"],
  150. [c_ptr, event.code, event.reason, was_clean]
  151. );
  152. });
  153. return Module.IDHandler.add(socket);
  154. }, _js_id, str.utf8().get_data(), proto_string.utf8().get_data());
  155. /* clang-format on */
  156. if (peer_sock == -1)
  157. return FAILED;
  158. static_cast<Ref<EMWSPeer> >(_peer)->set_sock(peer_sock, _in_buf_size, _in_pkt_size);
  159. return OK;
  160. };
  161. void EMWSClient::poll() {
  162. }
  163. Ref<WebSocketPeer> EMWSClient::get_peer(int p_peer_id) const {
  164. return _peer;
  165. }
  166. NetworkedMultiplayerPeer::ConnectionStatus EMWSClient::get_connection_status() const {
  167. if (_peer->is_connected_to_host()) {
  168. if (_is_connecting)
  169. return CONNECTION_CONNECTING;
  170. return CONNECTION_CONNECTED;
  171. }
  172. return CONNECTION_DISCONNECTED;
  173. };
  174. void EMWSClient::disconnect_from_host(int p_code, String p_reason) {
  175. _peer->close(p_code, p_reason);
  176. };
  177. IP_Address EMWSClient::get_connected_host() const {
  178. ERR_FAIL_V_MSG(IP_Address(), "Not supported in HTML5 export.");
  179. };
  180. uint16_t EMWSClient::get_connected_port() const {
  181. ERR_FAIL_V_MSG(0, "Not supported in HTML5 export.");
  182. };
  183. int EMWSClient::get_max_packet_size() const {
  184. return (1 << _in_buf_size) - PROTO_SIZE;
  185. }
  186. Error EMWSClient::set_buffers(int p_in_buffer, int p_in_packets, int p_out_buffer, int p_out_packets) {
  187. _in_buf_size = nearest_shift(p_in_buffer - 1) + 10;
  188. _in_pkt_size = nearest_shift(p_in_packets - 1);
  189. return OK;
  190. }
  191. EMWSClient::EMWSClient() {
  192. _in_buf_size = nearest_shift((int)GLOBAL_GET(WSC_IN_BUF) - 1) + 10;
  193. _in_pkt_size = nearest_shift((int)GLOBAL_GET(WSC_IN_PKT) - 1);
  194. _is_connecting = false;
  195. _peer = Ref<EMWSPeer>(memnew(EMWSPeer));
  196. /* clang-format off */
  197. _js_id = EM_ASM_INT({
  198. return Module.IDHandler.add($0);
  199. }, this);
  200. /* clang-format on */
  201. };
  202. EMWSClient::~EMWSClient() {
  203. disconnect_from_host();
  204. _peer = Ref<EMWSPeer>();
  205. /* clang-format off */
  206. EM_ASM({
  207. Module.IDHandler.remove($0);
  208. }, _js_id);
  209. /* clang-format on */
  210. };
  211. #endif // JAVASCRIPT_ENABLED