|
基本数据类型byte与int
1. 添加Socket库和NetWorking库2. 一个实用网络类
1. 添加Socket库和NetWorking库
打开该文件
添加Sockets和Networking
关闭引擎,退出,重新开始
此时,你将会成功 的引入网络库
2. 一个实用网络类
- // Fill out your copyright notice in the Description page of Project Settings.#pragmaonce#include"HAL/Runnable.h"#include"CoreMinimal.h"#include"GameFramework/Actor.h"#include"Sockets.h"#include"Sockets.h"#include"SocketSubsystem.h"#include"Networking/Public/Interfaces/IPv4/IPv4Address.h"#include"SocketSubsystem.h"
- class FRunableThread;
- class AClient : public FRunnable
- {
- public:// Sets default values for this actor's propertiesAClient();
- virtual bool Init();
- virtual uint32 Run() override;
- virtual voidStop() override;
- virtual voidExit() override;
- FSocket* socket;
- bool SocketCreate(FString IPStr, int32 port);//int byte2 Buffer();
- FIPv4Address ip;~AClient();
- TQueue<int32> messages;
- FRunnableThread* Thread = nullptr;
- int32 stop = false;};
复制代码- // Fill out your copyright notice in the Description page of Project Settings.#include"Client.h"
- AClient::AClient(){
- this->SocketCreate("127.0.0.1",9201);
- Thread = FRunnableThread::Create(this,TEXT("This is my thread example"));
- stop =1;}
- bool AClient::Init(){
- stop =1;return true;}
- uint32 AClient::Run(){
- TArray<uint8> buffer;
- uint8 element =0;while(stop ==1){
- int32 len =0;
- buffer.Init(element,1024);
- socket->Recv(buffer.GetData(),buffer.Num(),len);auto val =FString(ANSI_TO_TCHAR(reinterpret_cast<constchar*>(buffer.GetData())));UE_LOG(LogTemp, Warning,TEXT("server info %s,%d,%d"),*val,len,stop)
- FPlatformProcess::Sleep(0.1);}UE_LOG(LogTemp, Warning,TEXT("thread end..."));return1;}void AClient::Stop(){
- stop =0;
- socket->Close();}void AClient::Exit(){}
- bool AClient::SocketCreate(FString IPStr, int32 port){
- FIPv4Address::Parse(IPStr, ip);
- TSharedPtr<FInternetAddr> addr = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->CreateInternetAddr();
- addr->SetIp(ip.Value);
- addr->SetPort(port);
- socket = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->CreateSocket(NAME_Stream,TEXT("default"), false);if(socket->Connect(*addr)){UE_LOG(LogTemp, Warning,TEXT("Connect Succeed!"));return true;}else{UE_LOG(LogTemp, Warning,TEXT("Connect Failed!"));return false;}}
- AClient::~AClient(){UE_LOG(LogTemp,Warning,TEXT("Client Destruct"))
- stop =0;}
复制代码 |
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有账号?立即注册
×
|