UE 4 TCP socket客户端,(TCP socket 插件)

在.h中

UCLASS()
class EXAMPLE_API ACppSocketConnection : public ATcpSocketConnection
{
	GENERATED_BODY()
 public:
	UFUNCTION()
	void OnConnected(int32 ConnectionId);

	UFUNCTION()
	void OnDisconnected(int32 ConId);

	UFUNCTION()
	void OnMessageReceived(int32 ConId, TArray<uint8>& Message);
  
  	UFUNCTION(BlueprintCallable)
	void ConnectToGameServer();
	
	UPROPERTY()
	int32 connectionIdGameServer;
}

在.cpp中

void ACppSocketConnection::ConnectToGameServer() {
	if (isConnected(connectionIdGameServer))
	{
		UE_LOG(LogError, Log, TEXT("Log: Can't connect SECOND time. We're already connected!"));
		return;
	}
	FTcpSocketDisconnectDelegate disconnectDelegate;
	disconnectDelegate.BindDynamic(this, &ACppSocketConnection::OnDisconnected);
	FTcpSocketConnectDelegate connectDelegate;
	connectDelegate.BindDynamic(this, &ACppSocketConnection::OnConnected);
	FTcpSocketReceivedMessageDelegate receivedDelegate;
	receivedDelegate.BindDynamic(this, &ACppSocketConnection::OnMessageReceived);
	Connect("127.0.0.1", 3500, disconnectDelegate, connectDelegate, receivedDelegate, connectionIdGameServer);
}

void ACppSocketConnection::OnConnected(int32 ConId) {
	UE_LOG(LogTemp, Log, TEXT("Log: Connected to server."));
}

void ACppSocketConnection::OnDisconnected(int32 ConId) {
	UE_LOG(LogTemp, Log, TEXT("Log: OnDisconnected."));
}

void ACppSocketConnection::OnMessageReceived(int32 ConId, TArray<uint8>& Message) {
	UE_LOG(LogTemp, Log, TEXT("Log: Received message."));
  	// In this example, we always encode messages a certain way:
  	// The first 4 bytes contain the length of the rest of the message.
  	while (Message.Num() != 0) {
		// read expected length
		int32 msgLength = Message_ReadInt(Message);
		if (msgLength == -1) // when we can't read 4 bytes, the method returns -1
			return;
		TArray<uint8> yourMessage;
		// read the message itself
		if (!Message_ReadBytes(msgLength, Message, yourMessage)) {
			// If it couldn't read expected number of bytes, something went wrong.
			// Print a UE_LOG here, while your project is in development.
			continue;
		}
		// If the message was read, then treat "yourMessage" here!
		// ...
		// And then we go back to the "while", because we may have received multiple messages in a frame, 
		// so they all have to be read.
  	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值