记录UE4中WebSocket和Json的使用方法(C++使用,蓝图没有的,想在蓝图用可以C++暴露方法给蓝图)。本文记录如何在UE4中使用WebSockets模块实现Client,在Python中实现Server,进行通信。
内容:
- UE4 WebSocket Client
- Python WebSocket Server
- UE4 Json
UE4.25.3。项目github:
https://github.com/tiax615/UE4_Networkgithub.com1. UE4 WebSocket Client
UE4中使用WebSocket,感觉这方面资料很少。百度里只会搜到一些蓝图插件,我曾用过一个,不够稳定(不如自己写);谷哥也没有太多内容,讲的比较详细的是一个社区的wiki,但也有错误的地方。
但实际上在UE4中用起来很方便。
WebSocket这个协议,能轻松和Web进行通信,而且很多语言都有WS的库,应用广泛。
1.1. 增加模块
增加WebSockets模块。关闭IDE,右键uproject项目文件->Generate Visual Studio project files,重新生成项目文件(不重新生成也许也可以):
// Copyright Epic Games, Inc. All Rights Reserved.
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可能会需要作为单例)
新建一个Actor类,叫做ActorWebSocket。为了使用WS,需要包含头文件:
#include "WebSocketsModule.h"
#include "IWebSocket.h"
在BeginPlay时,加载WebSockets模块:
// Called when the game starts or when spawned
void AActorWebSocket::BeginPlay()
{
Super::BeginPlay();
FModuleManager::Get().LoadModuleChecked("WebSockets");
}
注意wifi中这个写法是错误的,没有使用Get&#