当前位置: 首页 > article >正文

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;


	/// <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"); // Topic
		UE_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"); // 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, "手动关闭");

		
	}
}

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


http://www.kler.cn/a/161827.html

相关文章:

  • C++编程技巧与规范-类和对象
  • Leecode热题100-35.搜索插入位置
  • 【大数据测试HBase数据库 — 详细教程(含实例与监控调优)】
  • Android Studio 将项目打包成apk文件
  • Vue 项目打包后环境变量丢失问题(清除缓存),区分.env和.env.*文件
  • android dvr黑屏
  • JAVA IO:NIO
  • IntelliJ IDEA 2023.3 最新变化
  • 力扣每日一题day30[226. 翻转二叉树]
  • Web server failed to start. Port 8888 was already in use.
  • 点评项目——商户查询缓存
  • 前端实现token无感刷新的原因和步骤
  • Linux Docker 安装Nginx
  • 【Linux】Java 程序员必会的 Linux 最常用的命令
  • 小纸条..
  • ubuntu源配置文件/etc/apt/sources.list不存在
  • C语言实现水仙花
  • PostgreSQL 技术内幕(十二) CloudberryDB 并行化查询之路
  • Python文件操作(txt + xls + json)
  • class035 数据结构设计高频题【算法】
  • Chromium包含的内容(引擎)
  • Eureka的使用说明
  • 【react】动态页面转换成html文件下载,解决样式问题
  • Pytorch CIFAR10图像分类 Swin Transformer篇
  • 学会使用这个魔法棒,再也不用在容器里安装乱七八糟的命令工具了!
  • 数据结构如何影响程序的错误检测和调试?