UE Websocket笔记

参考链接

[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;


	/// 
	/// 连接成功
	/// 
	UFUNCTION()
	void OnConnectedCallback();

	/// 
	/// 连接错误
	/// 
	/// 
	UFUNCTION()
	void OnConnectionErrorCallback(const FString& Error);

	/// 
	/// 接收数据
	/// 
	/// 
	UFUNCTION()
	void OnReceivedMessageCallback(const FString& Message);

	/// 
	/// 关闭回调
	/// 
	/// 
	/// 
	/// 
	UFUNCTION()
	void OnClosedCallback(int32 Code, const FString& Reason, bool bWasClean);

	/// 
	/// 连接服务器
	/// 
	/// 
	UFUNCTION(BlueprintCallable, Category = "Vince|Network")
	void ConnectToServer(const FString URL);

	/// 
	/// 发送信息
	/// 
	/// 
	UFUNCTION(BlueprintCallable, Category = "Vince|Network")
	void SendMessage(const FString Message);

	/// 
	/// 手动关闭
	/// 
	UFUNCTION(BlueprintCallable, Category = "Vince|Network")
	void Disconnect();

	TSharedPtrSocket;
	
};
.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 RootObj = MakeShareable(new FJsonObject());
	TSharedRef> JsonReader = TJsonReaderFactory<>::Create(Message);

	if (FJsonSerializer::Deserialize(JsonReader, RootObj)) // 通过JsonReader读取RootObj
	{
		FString Topic = RootObj->GetStringField("Topic"); // Topic
		UE_LOG(LogTemp, Warning, TEXT("%s Topic:%s"), *FString(__FUNCTION__), *Topic);

		TSharedPtr ListObj = MakeShareable(new FJsonObject());
		ListObj = RootObj->GetObjectField("List"); // List 

		FString Key = ListObj->GetStringField("Key"); // Key
		UE_LOG(LogTemp, Warning, TEXT("%s Key:%s"), *FString(__FUNCTION__), *Key);

		float Value = ListObj->GetNumberField("Value"); // Value
		GEngine->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, "手动关闭");

		
	}
}

UE Websocket笔记_第1张图片

Websoket 地址前缀只能是ws/wss/wss+insecure

UE Websocket笔记_第2张图片

你可能感兴趣的:(虚幻引擎,笔记)