ue4 +python tcp通信

ue4中 cpp文件
// Fill out your copyright notice in the Description page of Project Settings.
#include “MyActor.h”
#include

#include “Object.h”
#include “Runtime/Networking/Public/Networking.h”

// Sets default values
AMyActor::AMyActor()
{
// 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;
SocketClient = NULL;

}

// Called when the game starts or when spawned
void AMyActor::BeginPlay()
{
Super::BeginPlay();
}

void AMyActor::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
Super::EndPlay(EndPlayReason);
UWorld* World = GetWorld();

GetWorld()->GetTimerManager().ClearTimer(TCPConnectionListenerTimerHandle);
GetWorld()->GetTimerManager().ClearTimer(TCPSocketListenerTimerHandle);

if (ConnectionSocket != NULL) {
	ConnectionSocket->Close();
}
if (ListenerSocket != NULL) {
	ListenerSocket->Close();
}

if (SocketClient) {
	SocketClient->Close();
	ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->DestroySocket(SocketClient);
}

}

// Called every frame
void AMyActor::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);

}

bool AMyActor::SocketCreate(FString IPStr, int32 port) {
FIPv4Address::Parse(IPStr, ip);

TSharedRef addr = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->CreateInternetAddr();
addr->SetIp(ip.Value);
addr->SetPort(port);

SocketClient = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->CreateSocket(NAME_Stream, TEXT("default"), false);

if (SocketClient->Connect(*addr))
{
	GEngine->AddOnScreenDebugMessage(1, 2.0f, FColor::Green, TEXT("Connect Succ!"));
	UE_LOG(LogTemp, Warning, TEXT("Connect Succ!"));
	return true;
}
else
{
	GEngine->AddOnScreenDebugMessage(1, 2.0f, FColor::Green, TEXT("Connect failed!"));
	UE_LOG(LogTemp, Warning, TEXT("Connect failed!"));
	return false;
}

}

void AMyActor::SocketSend(FString meesage)
{
TCHAR *seriallizedChar = meesage.GetCharArray().GetData();
int32 size = FCString::Strlen(seriallizedChar) + 1;
int32 sent = 0;

if (SocketClient->Send((uint8*)TCHAR_TO_UTF8(seriallizedChar), size, sent))
{
	GEngine->AddOnScreenDebugMessage(1, 2.0f, FColor::Green, TEXT("_____Send Succ!"));
	UE_LOG(LogTemp, Warning, TEXT("_____Send Succ!"));
}
else
{
	GEngine->AddOnScreenDebugMessage(1, 2.0f, FColor::Green, TEXT("_____Send failed!"));
	UE_LOG(LogTemp, Warning, TEXT("_____Send failed!"));
}

}

void AMyActor::SocketReceive(bool & bReceive, FString & recvMessage)
{
recvMessage = “”;
bReceive = false;
if (!SocketClient)
{
return;
}

TArray ReceiveData;
uint32 size;
uint8 element = 0;
while (SocketClient->HasPendingData(size))
{
	ReceiveData.Init(element, FMath::Min(size, 65507u));

	int32 read = 0;
	SocketClient->Recv(ReceiveData.GetData(), ReceiveData.Num(), read);

}

if (ReceiveData.Num() <= 0)
{
	return;
}
FString log = "Total Data read! num: " + FString::FromInt(ReceiveData.Num() <= 0);

GEngine->AddOnScreenDebugMessage(1, 2.0f, FColor::Green, log);
UE_LOG(LogTemp, Warning, TEXT("Recv log:   %s"), *log);

const FString ReceivedUE4String = StringFromBinaryArray(ReceiveData);

log = "Server:" + ReceivedUE4String;
GEngine->AddOnScreenDebugMessage(1, 2.0f, FColor::Green, log);
UE_LOG(LogTemp, Warning, TEXT("*** %s"), *log);

recvMessage = ReceivedUE4String;

bReceive = true;

}

FString AMyActor::StringFromBinaryArray(TArray BinaryArray)
{
return FString(ANSI_TO_TCHAR(reinterpret_cast(BinaryArray.GetData())));
}

.h文件
// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include “CoreMinimal.h”
#include “GameFramework/Actor.h”
#include “Object.h”
#include “Json.h”
#include “Networking/Public/Networking.h”
#include “MyActor.generated.h”
UCLASS()
class TCPTEST_API AMyActor : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor’s properties
AMyActor();

protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;

public:
// Called every frame
virtual void Tick(float DeltaTime) override;
FSocket* ListenerSocket;
FSocket* ConnectionSocket;
FIPv4Endpoint RemoteAddressForConnection;

FTimerHandle TCPSocketListenerTimerHandle;
FTimerHandle TCPConnectionListenerTimerHandle;







UFUNCTION(BlueprintCallable, Category = "MySocket")
	bool SocketCreate(FString IPStr, int32 port);

UFUNCTION(BlueprintCallable, Category = "MySocket")
	void SocketSend(FString meesage);

UFUNCTION(BlueprintPure, Category = "MySocket")
	void SocketReceive(bool& bReceive, FString& recvMessage);

FString StringFromBinaryArray(TArray BinaryArray);

FSocket *SocketClient;

FIPv4Address ip;

};

创建蓝图

ue4 +python tcp通信_第1张图片

python测试文件

#encoding=utf-8
# 创建一个 TCP 服务器程序,这个程序会把客户发送过来的字
# 符串加上一个时间戳(格式:'[时间]数据')返回给客户。
from socket import *
from time import ctime

host = '127.0.0.1'
port = 1081
bufsiz = 2048
addr = (host,port)

# ss = socket() # 创建服务器套接字
# ss.bind() # 把地址绑定到套接字上
# ss.listen() # 监听连接
# inf_loop: # 服务器无限循环
# cs = ss.accept() # 接受客户的连接
# comm_loop: # 通讯循环
# cs.recv()/cs.send() # 对话(接收与发送)
# cs.close() # 关闭客户套接字
# ss.close() # 关闭服务器套接字(可选)

#创建tcp套接字,绑定,监听
tcpServerSock = socket(AF_INET,SOCK_STREAM)#创建TCP Socket
#AF_INET 服务器之间网络通信
#socket.SOCK_STREAM 流式socket , for TCP
tcpServerSock.bind(addr)#将套接字绑定到地址, 
#在AF_INET下,以元组(host,port)的形式表示地址.
tcpServerSock.listen(5)#操作系统可以挂起的最大连接数量,至少为1,大部分为5

while True:
    print ('waiting for connection')
    # udp中是recvfrom(buffersize),tcp这里用accept();
    # tcp这里接收到的是客户端的sock对象,后面接受数据时使用socket.recv()
    tcpClientSock, addr2 = tcpServerSock.accept() #接受客户的连接
#接受TCP连接并返回(conn,address),其中conn是新的套接字对象,
#可以用来接收和发送数据。
#address是连接客户端的地址。
    print ('connected from :',addr2)

    while True:
        data = tcpClientSock.recv(bufsiz) #接收客户端发来的数据
        if not data:
            break
        print(data.decode())
        msg=input('请输入:')
        if not msg:
            break;
        tcpClientSock.send(msg.encode()) #返回给客户端数据
    tcpClientSock.close()
tcpServerSock.close()

参考https://blog.csdn.net/tianxiaojie_blog/article/details/78289565

你可能感兴趣的:(ue4,ue4,tcp,python)