我正在将 UE4 项目(版本 4.23)导出到 HTML5,并在
WebSockets
中启用了 .Build.cs
模块:
PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "WebSockets" });
在编辑器中玩时效果很好,但是当我在导出的项目上调用
FWebSocketsModule::Get().CreateWebSocket(url, protocol)
时,找不到此方法。
检查了
FWebSocketsModule.cpp
并声明了函数:
#if WITH_WEBSOCKETS
TSharedRef<IWebSocket> FWebSocketsModule::CreateWebSocket(....
....
#endif
因此,导出/运行到 html 时,
WITH_WEBSOCKETS
设置为 0
我确实在我的类上声明了这个宏并设置为1,但它在浏览器中卡在
Loading engine...
我是否遗漏了任何配置?
通过包含 emscripten websockets 设法从 HTML 调用 websockets
在
<Project>.Build.cs
构造函数中:
if (Target.Platform == UnrealTargetPlatform.HTML5)
{
string libwebs = "<Engine instal dir>/UE_4.23/Engine/Extras/ThirdPartyNotUE/emsdk/emscripten/1.38.31/src/library_websocket.js";
PublicAdditionalLibraries.Add(libwebs);
}
在我的 GameInstance.h 类中(或者每当你想注册 websockets 时):
#ifdef __EMSCRIPTEN__
#include <emscripten/html5.h>
#include <emscripten/emscripten.h>
#include <emscripten/websocket.h>
#endif
在 .cpp 类中:
#ifdef __EMSCRIPTEN__
static EMSCRIPTEN_WEBSOCKET_T socket;
static EM_BOOL onopen(int eventType, const EmscriptenWebSocketOpenEvent* websocketEvent, void* userData) {
//code logic ...
return EM_TRUE;
}
static EM_BOOL onerror(int eventType, const EmscriptenWebSocketErrorEvent* websocketEvent, void* userData) {
//code logic ...
return EM_TRUE;
}
static EM_BOOL onclose(int eventType, const EmscriptenWebSocketCloseEvent* websocketEvent, void* userData) {
//code logic ...
return EM_TRUE;
}
static EM_BOOL onmessage(int eventType, const EmscriptenWebSocketMessageEvent* websocketEvent, void* userData) {
Yourclass* instance = reinterpret_cast<YourClass*>(userData);
//code logic ...
instance->YourNonStaticFunc(..);
return EM_TRUE;
}
#endif
在您的 .cpp 初始化/方法中:
#ifdef __EMSCRIPTEN__
if (!emscripten_websocket_is_supported()) {
UE_LOG(LogTemp, Log, TEXT("\nemscripten_websocket not supoported :/\n"));
return;
}
EmscriptenWebSocketCreateAttributes ws_attrs = { TCHAR_TO_ANSI("ws://ip_address:port", NULL, EM_TRUE };
socket = emscripten_websocket_new(&ws_attrs);
emscripten_websocket_set_onopen_callback(socket, this, onopen);
emscripten_websocket_set_onerror_callback(socket, this, onerror);
emscripten_websocket_set_onclose_callback(socket, this, onclose);
emscripten_websocket_set_onmessage_callback(socket, this, onmessage);
#endif
有关 emscripten 函数的更多信息,您可以查看:
<Your engine install dir>/UE_4.23/Engine/Extras/ThirdPartyNotUE/emsdk/emscripten/1.38.31/system/include/emscripten/[websocket.h, emscripten.h, html5.h]
谢谢,你的回答对我帮助很大!!!