参考链接
[UE4 C++入门到进阶]12.Websocket网络通信 - 哔哩哔哩 包含怎么用Nodejs 写测试服务器
UE4_使用WebSocket和Json(上) - 知乎 包含Python写测试服务器
UE4_使用WebSocket和Json(下) - 知乎
示例代码
xxx.Build.cs"WebSockets"
.h#include "CoreMinimal.h"
#include "Subsystems/WorldSubsystem.h"
#include "IWebSocket.h"
#include "PTNetworkSubsystem.generated.h"/*** */
UCLASS()
class PIECETOGETHERTOOLS_API UPTNetworkSubsystem : public UWorldSubsystem
{GENERATED_BODY()virtual void Initialize(FSubsystemCollectionBase& Collection) override;virtual void Deinitialize() override;/// <summary>/// 连接成功/// </summary>UFUNCTION()void OnConnectedCallback();/// <summary>/// 连接错误/// </summary>/// <param name="Error"></param>UFUNCTION()void OnConnectionErrorCallback(const FString& Error);/// <summary>/// 接收数据/// </summary>/// <param name="Message"></param>UFUNCTION()void OnReceivedMessageCallback(const FString& Message);/// <summary>/// 关闭回调/// </summary>/// <param name="Code"></param>/// <param name="Reason"></param>/// <param name="bWasClean"></param>UFUNCTION()void OnClosedCallback(int32 Code, const FString& Reason, bool bWasClean);/// <summary>/// 连接服务器/// </summary>/// <param name="URL"></param>UFUNCTION(BlueprintCallable, Category = "Vince|Network")void ConnectToServer(const FString URL);/// <summary>/// 发送信息/// </summary>/// <param name="Message"></param>UFUNCTION(BlueprintCallable, Category = "Vince|Network")void SendMessage(const FString Message);/// <summary>/// 手动关闭/// </summary>UFUNCTION(BlueprintCallable, Category = "Vince|Network")void Disconnect();TSharedPtr<class IWebSocket>Socket;};
.cpp#include "PTNetworkSubsystem.h"
#include "WebSockets/Public/WebSocketsModule.h"
//#include "AsyncHttpObject.h"void UPTNetworkSubsystem::Initialize(FSubsystemCollectionBase& Collection)
{Super::Initialize(Collection);if (!FModuleManager::Get().IsModuleLoaded("WebSockets")){FModuleManager::Get().LoadModule("WebSockets");}}void UPTNetworkSubsystem::Deinitialize()
{Disconnect();Super::Deinitialize();
}void UPTNetworkSubsystem::OnConnectedCallback()
{UE_LOG(LogTemp, Warning, TEXT("连接成功"));
}void UPTNetworkSubsystem::OnConnectionErrorCallback(const FString& Error)
{UE_LOG(LogTemp, Warning, TEXT("连接错误,Error:%s"), *Error);
}void UPTNetworkSubsystem::OnReceivedMessageCallback(const FString& Message)
{UE_LOG(LogTemp, Warning, TEXT("收到消息,Message:%s"), *Message);/*示例{"Topic": "Unreal","List" : {"Key": "mood","Value" : 1.0}}*/TSharedPtr<FJsonObject> RootObj = MakeShareable(new FJsonObject());TSharedRef<TJsonReader<>> JsonReader = TJsonReaderFactory<>::Create(Message);if (FJsonSerializer::Deserialize(JsonReader, RootObj)) // 通过JsonReader读取RootObj{FString Topic = RootObj->GetStringField("Topic"); // TopicUE_LOG(LogTemp, Warning, TEXT("%s Topic:%s"), *FString(__FUNCTION__), *Topic);TSharedPtr<FJsonObject> ListObj = MakeShareable(new FJsonObject());ListObj = RootObj->GetObjectField("List"); // List FString Key = ListObj->GetStringField("Key"); // KeyUE_LOG(LogTemp, Warning, TEXT("%s Key:%s"), *FString(__FUNCTION__), *Key);float Value = ListObj->GetNumberField("Value"); // ValueGEngine->AddOnScreenDebugMessage(-1, 10.0f, FColor::Cyan, FString::Printf(TEXT("Value %d"), Value), true);}}void UPTNetworkSubsystem::OnClosedCallback(int32 Code, const FString& Reason, bool bWasClean)
{UE_LOG(LogTemp, Warning, TEXT("连接关闭,Code:%d,reason:%s"), Code, *Reason);
}void UPTNetworkSubsystem::ConnectToServer(const FString URL)
{//创建Websocket对象Socket = FWebSocketsModule::Get().CreateWebSocket(URL);// Bind Events// Socket->OnConnectionError().AddLambda([](const FString& Error)->// void{UE_LOG(LogTemp,Warning,TEXT("%s"),*Error)}); // Lambda绑定方式//绑定连接成功回调Socket->OnConnected().AddUObject(this, &UPTNetworkSubsystem::OnConnectedCallback);//绑定连接失败回调Socket->OnConnectionError().AddUObject(this, &UPTNetworkSubsystem::OnConnectionErrorCallback);//绑定连接关闭回调Socket->OnClosed().AddUObject(this, &UPTNetworkSubsystem::OnClosedCallback);//绑定收到消息回调Socket->OnMessage().AddUObject(this, &UPTNetworkSubsystem::OnReceivedMessageCallback);Socket->Connect();//UAsyncHttpObject::AsyncHttpDownload("https://t7.baidu.com/it/u=2621658848,3952322712&fm=193&f=GIF", FPaths::ProjectContentDir() + "Paks", "4");
}void UPTNetworkSubsystem::SendMessage(const FString Message)
{if (Socket.IsValid()){Socket->Send(Message);}
}void UPTNetworkSubsystem::Disconnect()
{if (Socket.IsValid()){UE_LOG(LogTemp, Warning, TEXT("手动关闭"));Socket->Close(1000, "手动关闭");}
}
* Websoket 地址前缀只能是ws/wss/wss+insecure