当前位置: 首页 > 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.lryc.cn/news/621893.html

相关文章:

  • tun/tap 转发性能优化
  • 记录一下 StarRocks 点查的 Profile Metrics
  • C++结构体详解
  • 局部变量与全局变量的关系及应用
  • 【swift开发】SwiftUI概述 SwiftUI 全面解析:苹果生态的声明式 UI 革命
  • Unity_导航网格
  • 什么是国产化防爆平板?有哪些功能特点?应用在什么场景?
  • Unity与OpenGL中的材质系统详解
  • 【完整源码+数据集+部署教程】孔洞检测系统源码和数据集:改进yolo11-RetBlock
  • 汽车线束高压屏蔽层接地设计
  • uniapp小程序ocr-navigator身份证拍照上传替换方案
  • 解决在uniapp真机运行上i18n变量获取不到问题
  • USB ADB 简介
  • 为什么游戏会出现“卡顿”:`clock.tick()` v.s. `clock.get_fps()`
  • 【Cuda 编程思想】LinearQaunt-分块量化矩阵乘法计算过程
  • 25. 移动端-uni-app
  • 【URP】[光栅阶段][光栅插值]Unity透视校正插值
  • 2025年最新政策下,劳务报酬的增值税应该如何计算?
  • MqSQL中的《快照读》和《当前读》
  • Prometheus 监控 Kubernetes Cluster 最新极简教程
  • [论文笔记] WiscKey: Separating Keys from Values in SSD-Conscious Storage
  • DeepSeek-V2:一种强大、经济且高效的混合专家语言模型
  • 在 macOS 上顺利安装 lapsolver
  • 从根本上解决MAC权限问题(关闭sip)
  • vue3 wangeditor5 编辑器,使用方法
  • demo 通讯录 + 城市选择器 (字母索引左右联动 ListItemGroup+AlphabetIndexer)笔记
  • 分布式锁:从理论到实战的深度指南
  • 【机器人-基础知识】ROS常见功能架构
  • 微软自曝Win 11严重漏洞:可导致全盘数据丢失
  • Kafka生产者原理深度解析