[UE4] TCP Socket 傳輸實現
程式碼
需要注意的地方
記得在Build.cs添加Sockets, Networking
TcpClient.h
virtual bool SocketReceive();
//這裡添加virtual關鍵字是為了未來覆載此方法來實現從封包中拆解出自訂的資料格式
TcpClient.cpp
可在ATcpClient::ATcpClient() {...}建構函式中給予資料成員一個初始值,避免資料異常
若你想同步變數
ATcpClient::ATcpClient()
{
bReplicates = true; // 啟用同步
}
// Replicate
void ATcpClient::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME(ATcpClient, Tcp_UpdateRate); // 你想同步的變數
}
在UE4停止運作時,確保有刪除Thread與關閉Socket
void ATcpClient::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
if (m_RecvThread != nullptr)
{
m_RecvThread->Kill(true);
delete m_RecvThread;
}
if (Socket)
{
Socket->Close();
ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->DestroySocket(Socket);
}
Super::EndPlay(EndPlayReason);
}
Byte to String & Byte to float
// Byte to String
FString(ANSI_TO_TCHAR(reinterpret_cast<const char*>(ReceiveData.GetData())));
// Byte to float
TArray<uint8> binaryData;
binaryData.Add(ReceiveData.GetData()[(3]);
binaryData.Add(ReceiveData.GetData()[(2]);
binaryData.Add(ReceiveData.GetData()[(1]);
binaryData.Add(ReceiveData.GetData()[(0]);
decodeFloat = *reinterpret_cast<float*>(binaryData.GetData());
參考資料
UE4 Sockets多線程TCP通信
記得在Build.cs添加Sockets, Networking
TcpClient.h
virtual bool SocketReceive();
//這裡添加virtual關鍵字是為了未來覆載此方法來實現從封包中拆解出自訂的資料格式
TcpClient.cpp
可在ATcpClient::ATcpClient() {...}建構函式中給予資料成員一個初始值,避免資料異常
若你想同步變數
ATcpClient::ATcpClient()
{
bReplicates = true; // 啟用同步
}
// Replicate
void ATcpClient::GetLifetimeReplicatedProps(TArray< FLifetimeProperty > & OutLifetimeProps) const
{
Super::GetLifetimeReplicatedProps(OutLifetimeProps);
DOREPLIFETIME(ATcpClient, Tcp_UpdateRate); // 你想同步的變數
}
在UE4停止運作時,確保有刪除Thread與關閉Socket
void ATcpClient::EndPlay(const EEndPlayReason::Type EndPlayReason)
{
if (m_RecvThread != nullptr)
{
m_RecvThread->Kill(true);
delete m_RecvThread;
}
if (Socket)
{
Socket->Close();
ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->DestroySocket(Socket);
}
Super::EndPlay(EndPlayReason);
}
Byte to String & Byte to float
// Byte to String
FString(ANSI_TO_TCHAR(reinterpret_cast<const char*>(ReceiveData.GetData())));
// Byte to float
TArray<uint8> binaryData;
binaryData.Add(ReceiveData.GetData()[(3]);
binaryData.Add(ReceiveData.GetData()[(2]);
binaryData.Add(ReceiveData.GetData()[(1]);
binaryData.Add(ReceiveData.GetData()[(0]);
decodeFloat = *reinterpret_cast<float*>(binaryData.GetData());
參考資料
UE4 Sockets多線程TCP通信