axmol/core/network/WebSocket-wasm.cpp

169 lines
5.8 KiB
C++
Raw Normal View History

/****************************************************************************
Copyright (c) 2019-present Axmol Engine contributors (see AUTHORS.md).
Release 2.1.5 (#2076) * Fix unexpected libpng used * Fix string format incorrect for tests * Fix #1751, use coroutine control AutoTest flow * Update CHANGELOG.md * Added OpenType font (.otf) to the noCompress list. (#2077) * Update 1k & copyright notice in some sources * Move doctest to axmol 3rdparty * Fix ci * Update 1kdist to v90 * Update 1kiss.ps1 * DrawNodeV2 0.95.1 (#2079) * Rename remaining legacy engine related spells and improve code style * Update 3rdparty README.md * Fix checkReallySupportsASTC does not work on ios device reported by @BIGCATDOG in https://github.com/axmolengine/axmol/issues/2078 * Fix ci * FastRNG: add missing include for AXASSERT (#2081) * Delete unused files * Improve FileUtils - Rename FileUtils::createDirectory to FileUtils::createDirectories - Use splitpath_cb to optimize FileUtils::createDirectories - Rename FileUtils::getFileShortName to FileUtils::getPathBaseName - Rename FileUtils::getFileExtension to FileUtils::getPathExtension - Add FileUtils::getPathDirName - Add FileUtils::getPathBaseNameNoExtension - Mark all renamed FileUtils stubs old name deprecated - Mark all FileUtils offthread APIs deprecated * Update box2d to v2.4.2 * Disable /sdl checks explicitly for winuwp For axmol deprecated policy, we need disable /sdl checks explicitly to avoid compiler traits invoking deprecated functions as error * Update cppwinrt to 2.0.240405.15 * Update simdjson to 3.10.0 * Fix box2d testbed compile error * Improve file path to url * Fix FileUtils::createDirectories unix logic * axmol-cmdline: remove arch suffix for host build output directory * Update CHANGELOG.md * Update lua bindings --------- Co-authored-by: Dani Alias <danielgutierrezalias@gmail.com> Co-authored-by: aismann <icesoft@freenet.de> Co-authored-by: smilediver <smilediver@outlook.com>
2024-08-11 21:11:35 +08:00
https://axmol.dev
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
2023-12-31 22:23:25 +08:00
#include "network/WebSocket-wasm.h"
#include "yasio/errc.hpp"
#include "base/Logging.h"
2023-12-31 22:23:25 +08:00
NS_AX_BEGIN
namespace network
{
EM_BOOL WebSocket::em_ws_onopen(int eventType, const EmscriptenWebSocketOpenEvent* websocketEvent, void* userData)
{
auto ws = static_cast<WebSocket*>(userData);
if (!ws || !ws->_delegate)
return EM_TRUE;
ws->_state = WebSocket::State::OPEN;
ws->_delegate->onOpen(ws);
return EM_TRUE;
}
EM_BOOL WebSocket::em_ws_onerror(int eventType, const EmscriptenWebSocketErrorEvent* websocketEvent, void* userData)
{
auto ws = static_cast<WebSocket*>(userData);
if (!ws || !ws->_delegate)
return EM_TRUE;
ws->_state = WebSocket::State::CLOSED;
ws->_delegate->onError(ws, ErrorCode::CONNECTION_FAILURE);
return EM_TRUE;
}
EM_BOOL WebSocket::em_ws_onclose(int eventType, const EmscriptenWebSocketCloseEvent* websocketEvent, void* userData)
{
auto ws = static_cast<WebSocket*>(userData);
if (!ws || !ws->_delegate)
return EM_TRUE;
ws->_state = WebSocket::State::CLOSED;
ws->_delegate->onClose(ws);
return EM_TRUE;
}
EM_BOOL WebSocket::em_ws_onmessage(int eventType, const EmscriptenWebSocketMessageEvent* websocketEvent, void* userData)
{
auto ws = static_cast<WebSocket*>(userData);
if (!ws || !ws->_delegate)
return EM_TRUE;
WebSocket::Data dataView;
dataView.bytes = reinterpret_cast<const char*>(websocketEvent->data);
dataView.isBinary = !websocketEvent->isText;
dataView.len = websocketEvent->numBytes;
ws->_delegate->onMessage(ws, dataView);
return EM_TRUE;
}
WebSocket::WebSocket() {}
WebSocket::~WebSocket() {}
bool WebSocket::open(Delegate* delegate, std::string_view url, std::string_view caFilePath, std::string_view protocols)
2023-12-31 22:23:25 +08:00
{
if (url.empty())
{
AXLOGW("ws open fail, url is empty!");
2023-12-31 22:23:25 +08:00
return false;
}
_delegate = delegate;
_url = url;
_subProtocols = protocols;
EmscriptenWebSocketCreateAttributes ws_attrs = {_url.c_str(),
_subProtocols.empty() ? nullptr : _subProtocols.c_str(), EM_TRUE};
2023-12-31 22:23:25 +08:00
AXLOGD("ws open url: {}, protocols: {}", ws_attrs.url, ws_attrs.protocols);
2023-12-31 22:23:25 +08:00
_state = WebSocket::State::CONNECTING;
_wsfd = emscripten_websocket_new(&ws_attrs);
// chrome/edge can't connect
// firefox works with "Sec-Fetch-Site: cross-site" in request header
// refer: https://github.com/emscripten-core/emscripten/issues/19100
// wasm websocket callback thread same with axmol render thread
emscripten_websocket_set_onopen_callback(_wsfd, this, em_ws_onopen);
emscripten_websocket_set_onerror_callback(_wsfd, this, em_ws_onerror);
emscripten_websocket_set_onclose_callback(_wsfd, this, em_ws_onclose);
emscripten_websocket_set_onmessage_callback(_wsfd, this, em_ws_onmessage);
return true;
}
/**
* @brief Sends string data to websocket server.
*
* @param message string data.
* @lua sendstring
*/
void WebSocket::send(std::string_view message)
{
auto error = emscripten_websocket_send_utf8_text(_wsfd, message.data());
if (error)
AXLOGW("Failed to emscripten_websocket_send_binary(): {}", error);
2023-12-31 22:23:25 +08:00
}
/**
* @brief Sends binary data to websocket server.
*
* @param binaryMsg binary string data.
* @param len the size of binary string data.
* @lua sendstring
*/
void WebSocket::send(const void* data, unsigned int len)
{
auto error = emscripten_websocket_send_binary(_wsfd, const_cast<void*>(data), len);
if (error)
AXLOGW("Failed to emscripten_websocket_send_binary(): {}", error);
2023-12-31 22:23:25 +08:00
}
/**
* @brief Closes the connection to server synchronously.
* @note It's a synchronous method, it will not return until websocket thread exits.
*/
void WebSocket::close()
{
closeAsync(); // TODO
}
/**
* @brief Closes the connection to server asynchronously.
* @note It's an asynchronous method, it just notifies websocket thread to exit and returns directly,
* If using 'closeAsync' to close websocket connection,
* be careful of not using destructed variables in the callback of 'onClose'.
*/
void WebSocket::closeAsync()
{
// close code: Uncaught DOMException: Failed to execute 'close' on 'WebSocket':
// The code must be either 1000, or between 3000 and 4999. 1024 is neither.
EMSCRIPTEN_RESULT error =
emscripten_websocket_close(_wsfd, 3000 - yasio::errc::shutdown_by_localhost, "shutdown by localhost");
if (!error)
_state = WebSocket::State::CLOSING;
else
AXLOGW("Failed to emscripten_websocket_close(): {}", error);
2023-12-31 22:23:25 +08:00
}
} // namespace network
NS_AX_END