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

UE UDP通信

1.确保工程为C++工程,在项目工程的xx.Build.cs中加入Networking和Sockets模块。

PublicDependencyModuleNames.AddRange(new string[] { "Core", "CoreUObject", "Engine", "InputCore", "Networking", "Sockets"});

2.C++创建Actor,命名为UDPClient。

3.编写代码UDPClient.h和UDPClient.cpp实现UDP发送和接收功能。

// Fill out your copyright notice in the Description page of Project Settings.#pragma once#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Runtime/Sockets/Public/Sockets.h"
#include "Sockets/Public/SocketSubsystem.h"
#include "Runtime/Networking/Public/Common/UdpSocketBuilder.h"
#include "Runtime/Networking/Public/Common/UdpSocketReceiver.h"
#include "Networking/Public/Interfaces/IPv4/IPv4Address.h"
#include "UDPClient.generated.h"UCLASS()
class MYBLANK_API AUDPClient : public AActor
{GENERATED_BODY()public:	// Sets default values for this actor's propertiesAUDPClient();protected:// Called when the game starts or when spawnedvirtual void BeginPlay() override;virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;public:	// Called every framevirtual void Tick(float DeltaTime) override;public:FSocket* udpSocket;//远程的地址TSharedPtr<FInternetAddr> RemoteAddr;UFUNCTION(BlueprintCallable, Category = "UDP")bool CreateUdp(const FString& socketName, const FString& targetIP, const int32 targetPort, const int32 selfPort);UFUNCTION(BlueprintCallable, Category = "UDP")bool SendMsg(FString msg);UFUNCTION(BlueprintCallable, Category = "UDP")void RecvMsg(bool& result, FString& msg);};
// Fill out your copyright notice in the Description page of Project Settings.#include "UDPClient.h"// Sets default values
AUDPClient::AUDPClient()
{// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.PrimaryActorTick.bCanEverTick = true;udpSocket = NULL;
}// Called when the game starts or when spawned
void AUDPClient::BeginPlay()
{Super::BeginPlay();}// Called every frame
void AUDPClient::Tick(float DeltaTime)
{Super::Tick(DeltaTime);}void AUDPClient::EndPlay(const EEndPlayReason::Type EndPlayReason)
{Super::EndPlay(EndPlayReason);if (udpSocket){udpSocket->Close();ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->DestroySocket(udpSocket);}
}bool AUDPClient::CreateUdp(const FString& socketName, const FString& targetIP, const int32 targetPort, const int32 selfPort)
{bool bIsValid;RemoteAddr = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->CreateInternetAddr();RemoteAddr->SetIp(*targetIP, bIsValid);RemoteAddr->SetPort(targetPort);if (!bIsValid){UE_LOG(LogTemp, Warning, TEXT("CreateUdp>> IP address was not valid! "), *targetIP);return false;}int32 BufferSize = 2 * 1024 * 1024;FIPv4Endpoint Endpoint(FIPv4Address::Any, selfPort);  //所有ip地址本地udpSocket = FUdpSocketBuilder(*socketName).AsReusable().WithBroadcast() // 广播.WithSendBufferSize(BufferSize).AsNonBlocking().BoundToEndpoint(Endpoint).WithReceiveBufferSize(BufferSize);udpSocket->SetSendBufferSize(BufferSize, BufferSize);udpSocket->SetReceiveBufferSize(BufferSize, BufferSize);return bIsValid;
}bool AUDPClient::SendMsg(FString msg)//发送消息
{if (!udpSocket){UE_LOG(LogTemp, Warning, TEXT("No udpSocket"));return false;}int32 BytesSent = 0;FString serialized = msg;TCHAR* serializedChar = serialized.GetCharArray().GetData();int32 size = FCString::Strlen(serializedChar);int32 sent = 0;udpSocket->SendTo((uint8*)TCHAR_TO_UTF8(serializedChar), size, BytesSent, *RemoteAddr);if (BytesSent < 0){const FString Str = "Socket is valid but the receiver received 0 bytes, make sure it is listening properly!";UE_LOG(LogTemp, Error, TEXT("%s"), *Str);return false;}UE_LOG(LogTemp, Warning, TEXT("SendMsg Succcess! INFO msg = %s "), *msg);return true;
}void AUDPClient::RecvMsg(bool& result,FString& msg)//接收消息
{if (!udpSocket){UE_LOG(LogTemp, Warning, TEXT("No udpSocket"));result = false;}TSharedRef<FInternetAddr> targetAddr = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->CreateInternetAddr();TArray<uint8> ReceivedData;//定义一个接收器uint32 Size;if (udpSocket->HasPendingData(Size)){result = true;msg = "";uint8* Recv = new uint8[Size];int32 BytesRead = 0;ReceivedData.SetNumUninitialized(FMath::Min(Size, 65507u));udpSocket->RecvFrom(ReceivedData.GetData(), ReceivedData.Num(), BytesRead, *targetAddr);//创建远程接收地址char ansiiData[1024];memcpy(ansiiData, ReceivedData.GetData(), BytesRead);//拷贝数据到接收器ansiiData[BytesRead] = 0;                            //判断数据结束FString debugData = UTF8_TO_TCHAR(ansiiData);         //字符串转换msg = debugData;}else{result = false;}
}


FUdpSocketBuilder Functions介绍:

4.创建基于UDPClient的蓝图BP_MyUDPClient。

5.打开蓝图BP_MyUDPClient实现UDP实例化、发送和接收功能。

6.将蓝图BP_MyUDPClient放入场景中启动实现U3D和UE程序UDP通信。

http://www.dtcms.com/a/332127.html

相关文章:

  • 接口芯片断电高阻态特性研究与应用分析
  • UDP协议特点与网络通信
  • MIPI-csi调试
  • 物联网系统中传感器到网关到物联网平台的传输路径、协议、原理、用途与架构详解
  • 【机器学习深度学习】OpenCompass 评测指标全解析:让大模型评估更科学
  • tun/tap 转发性能优化
  • 当云手机出现卡顿怎么办?
  • 自适应UI设计解读 | Fathom 企业人工智能平台
  • 基于微信小程序的家教服务平台的设计与实现/基于asp.net/c#的家教服务平台/基于asp.net/c#的家教管理系统
  • Boost库中boost::function函数使用详解
  • OpenCV-循环读取视频帧,对每一帧进行处理
  • GoLand深度解析:智能开发利器与cpolar内网穿透方案的协同实践
  • 0814 TCP通信协议
  • 一款开源的远程桌面软件,旨在为用户提供流畅的游戏体验,支持 2K 分辨率、60 FPS,延迟仅为 40ms。
  • 数据库访问模式详解
  • [TryHackMe](知识学习)---基于堆栈得到缓冲区溢出
  • opencv基础学习与实战(2)
  • Linux中的日志管理
  • 学习嵌入式第二十八天
  • 中山清华:基于大模型的具身智能系统综述
  • app-4 日志上传
  • 从0到1:C++ 语法之引用
  • qt项目中解决关闭弹窗后执行主界面的信号槽时闪退问题
  • 基于wireshark的USB 全速硬件抓包工具USB Sniffer Lite的使用
  • 多线程安全和性能测试
  • 珠海社保缴费记录如何打印
  • MyBatis Interceptor 深度解析与应用实践
  • CTFShow PWN入门---Kernel PWN 356-360 [持续更新]
  • 【嵌入式汇编基础】-ARM架构基础(五)
  • c/c++实现 TCP Socket网络通信