using
UnrealBuildTool
;
public
class
UE4_Network
:
ModuleRules
public
UE4_Network
(
ReadOnlyTargetRules
Target
)
:
base
(
Target
)
PCHUsage
=
PCHUsageMode
.
UseExplicitOrSharedPCHs
;
PublicDependencyModuleNames
.
AddRange
(
new
string
[]
"Core"
,
"CoreUObject"
,
"Engine"
,
"InputCore"
,
"WebSockets"
});
// 增加WebSockets模块
PrivateDependencyModuleNames
.
AddRange
(
new
string
[]
{
});
// Uncomment if you are using Slate UI
// PrivateDependencyModuleNames.AddRange(new string[] { "Slate", "SlateCore" });
// Uncomment if you are using online features
// PrivateDependencyModuleNames.Add("OnlineSubsystem");
// To include OnlineSubsystemSteam, add it to the plugins section in your uproject file with the Enabled attribute set to true
1.2. 加载模块
wiki说In order to use this module, we need to load it. To do so, we will load it on game instance initialization(为了使用此模块,我们需要加载它。为此,我们将在游戏实例初始化时加载它),给出的例子是在GameInstance中Init的适合加载了模块。我尝试过在GameInstanceSubsystem的子类中加载,也可以正常使用,这两个类的生命周期相似。这次尝试在Actor中加载。(仅用来测试,不用在实际项目中,实际用的时候WS可能会需要作为单例)
// Called when the game starts or when spawned
voidAActorWebSocket::BeginPlay()Super::BeginPlay();FModuleManager::Get().LoadModuleChecked("WebSockets");
注意wifi中这个写法是错误的,没有使用Get:
// MyProjectGameInstance.cpp
#include"WebSocketsModule.h"voidUMyProjectGameInstance::Init()Super::Init();// Load the WebSockets module. An assertion will fail if it isn't found.
FWebSocketsModule&Module=FModuleManager::LoadModuleChecked(TEXT("WebSockets"));
1.3. 创建Socket,绑定事件
先在ActorWebSocket.h中定义一些变量:
public:// Sets default values for this actor's properties
AActorWebSocket();constFStringServerURL="ws://127.0.0.1:23333";constFStringServerProtocol="ws";TSharedPtr<IWebSocket>Socket=nullptr;
在ActorWebSocket.h中声明一些方法,用于绑定事件:
protected:// Called when the game starts or when spawned
virtualvoidBeginPlay()override;voidOnConnected();voidOnConnectionError(constFString&Error);voidOnClosed(int32StatusCode,constFString&Reason,boolbWasClean);voidOnMessage(constFString&Message);// 接收消息时
voidOnMessageSent(constFString&MessageString);// 发送消息时
// Called when the game starts or when spawned
voidAActorWebSocket::BeginPlay()Super::BeginPlay();FModuleManager::Get().LoadModuleChecked("WebSockets");Socket=FWebSocketsModule::Get().CreateWebSocket(ServerURL,ServerProtocol);// Bind Events
// Socket->OnConnectionError().AddLambda([](const FString& Error)->
// void{UE_LOG(LogTemp,Warning,TEXT("%s"),*Error)}); // Lambda不好看,改用绑定方法
Socket->OnConnected().AddUObject(this,&AActorWebSocket::OnConnected);Socket->OnConnectionError().AddUObject(this,&AActorWebSocket::OnConnectionError);Socket->OnClosed().AddUObject(this,&AActorWebSocket::OnClosed);Socket->OnMessage().AddUObject(this,&AActorWebSocket::OnMessage);Socket->OnMessageSent().AddUObject(this,&AActorWebSocket::OnMessageSent);