상세 컨텐츠

본문 제목

언리얼 엔진 네트워크 연동 관련

게임엔진관련/언리얼 엔진

by AlrepondTech 2020. 9. 20. 05:02

본문

반응형
728x170

 

 

 

 

=================================

=================================

=================================

 

 

 

 

 

출처: http://mypi.ruliweb.daum.net/mypi.htm?num=8864&id=pokapoka

 

Question>

unreal engine 4로 network game을 만들고 싶음.
어떤 문서들을 살펴 보면 되겠는가?

-------------------------------------------------------------

Answer>

unrelal engine 4의 network game 개발에 관련된 
공식 문서(Official Document) 주소는 아래와 같습니다.

https://docs.unrealengine.com/latest/KOR/Programming/Online/index.html
https://docs.unrealengine.com/latest/KOR/Resources/SampleGames/ShooterGame/index.html


network 처리를 세부적으로 설명한 문서의 주소 아래와 같습니다.
(unreal engine 3 기준)

http://udn.epicgames.com/Three/NetworkingOverviewKR.html


replication을 설명한 자료는 아래와 같고요.
(unreal engine 3 기준)

http://udn.epicgames.com/Three/ReplicationHomeKR.html


replication 관련 console command를 간단하게 설명한 자료는 아래와 같습니다.
(unreal engine 3 기준)

http://cafe.naver.com/igc123/27
http://cafe.daum.net/igc123/K3VE/21


참고하셔서 project에 맞는 source를 구성해 보시기 바랍니다.^^


P.S.
unreal engine 4부터는 C++로 접근하는 게 기본이라서,
위 문서들 전부 무시하고, 새로 network module을 만드시는 게 더 좋을 수도 있습니다.^^
(다만, 동기화에 자신이 있는 경우에만 그렇게 하시기 바랍니다.^^;;;;;;;;)



Tag:
안기훈, Kee Hoon Ahn, Unreal, UDK, iPhone, iPad, app, 앱, iOS

 

 

=================================

=================================

=================================

 

 

 

출처: http://www.gpgstudy.com/forum/viewtopic.php?p=89422

 

언리얼3 엔진의 네트웍 라이브러리 그대로 사용하나요? 올려짐: 2007-10-27 09:32

인용과 함께 답변  이 게시물을 del.icio.us에 추가

언리얼 2.x 제외하고 언리얼 3엔진에 대해서만 질문 드리겠습니다. 

언리얼 3 엔진으로 개발시 엔진에 있는 네트웍 라이브러리를 어떻게 사용하는지 궁금합니다. 

 

질문은 다음과 같습니다. 간단하게 답변만 해주셔도 고맙겠습니다. 

 

1. MMORPG 개발시 언리얼엔진의 네트웍 라이브러리를 사용하나요? 

 

 

 

2. 스페셜포스와 같은 온라인 FPS 게임을 만들때 언리얼 네트웍 라이브러리를 사용하나요? 

 

 

 

경험자 분들의 간단한 답변을 기다립니다. 

 

 

그럼 좋은 주말 보내세요.

위로

 

비회원

손님

 

 

 

올리기간단하게 답변드립니다. 올려짐: 2007-10-27 09:57

인용과 함께 답변  이 게시물을 del.icio.us에 추가

안씁니다. 현재 최신 빌드의 언리얼 엔진 3에 들어있는 네트웍 라이브러리라도 MMO용으로 쓰기엔 무리입니다. 

 

IpDrv 모듈을 거의 척출해내고 MMO용 네트웍 엔진을 삽입해야합니다. (경험담) 

 

이건 어떤 엔진이라도 마찬가지입니다. 

 

스페셜포스와 같은 MMO가 아닌 온라인 FPS라면 적당히 손봐서 사용할수도 있을 것 같습니다.

위로

 

비회원

손님

 

 

 

올리기 올려짐: 2007-10-27 09:59

인용과 함께 답변  이 게시물을 del.icio.us에 추가

UDN에 보면 소니가 네트웍에 관해 많이 올려놓은 것 같더군요. 그쪽도 참고해보세요.

위로

 

비회원

손님

 

 

 

올리기 올려짐: 2007-10-28 02:45

인용과 함께 답변  이 게시물을 del.icio.us에 추가

언리얼3엔진이나 크라이2엔진이나 쥬피터EX엔진이나 MMOG를 만든다면 거기 딸려있는 네트웍 엔진은 버려야합니다.

위로

 

비회원

손님

 

 

 

올리기 올려짐: 2007-10-28 04:24

인용과 함께 답변  이 게시물을 del.icio.us에 추가

언리얼 3앤진이라도 mmog용 네트웍은 새로 작성해야합니다. 그래도 언리얼 3엔진은 상황이 많이 좋습니다. 크라이텍 엔진이나 쥬피터 엔진은 네트웍이 엔진 내부 코드랑 많이 연계되어 있어서 분리하려면 많은 고난이 필요합니다.

위로

 

비회원

손님

 

 

 

올리기 올려짐: 2007-10-28 07:52

인용과 함께 답변  이 게시물을 del.icio.us에 추가

IpDrv를 거의 새로 작성하지만 완전히 삭제하고 새로 넣을 필요까지는 없습니다. 프레임웍만 적당히 남겨두고 내부를 바꿔도 됩니다. 그리고 UE3 IPP로 네트웍 라이브러리들이 나와있으므로 그것들을 고려해보는것도 괜찮을겁니다.

위로

 

비회원

손님

 

 

 

 

 

올리기 올려짐: 2007-10-28 07:59

인용과 함께 답변  이 게시물을 del.icio.us에 추가

언리얼 엔진 3는 계속 엔진이 업데이트 되면서 코드의 구성이 서서히 바뀌어 가는 부분도 많죠. 네트웍 부분을 보면 언리얼 엔진 3가 MMOG로 쓰이는 게임들이 점점 늘어나 가면서 네트웍과 물리의 충돌감지 및 예측과 네트웍이 분리되면서도 쉽게 연동 가능하게 코드가 수정되서 네트웍 모듈의 교체는 쉽게되어 있습니다. 뭐 필요한게 있다면 계속 에픽을 볶아서 요구해야 앞으로도 필요한 여러 부분에 대한 수정이 많이 이루어지게 될겁니다.

위로

 

하늘치

 

 

 

가입: 2007년 10월 2일

올린 글: 8

소속: 우리집

올리기. 올려짐: 2007-10-28 15:27

인용과 함께 답변  이 게시물을 del.icio.us에 추가

MMO의 경우, 언리얼의 네트워크 관련 모든 기능을 쓰지 않으면 되니 차라리 편해요. (서버 플머 입장) 

단순히 소켓 통신 모듈을 교체하는 걸로 해결이 되는 문제가 아니라 구조적으로 맞지 않으니까요. 

단, 언리얼은 옵션 하나만 바꾸면 저절로 멀티플레이가 되고 비공정 타고 날라다니는데 작업할 것이 뭐가 있냐고 묻는 피디를 잘 설득하셔야 합니다. orz 

리니지2와 라그2가 언리얼의 네트워크 기능을 아예 포기하고 개발한 걸로 알아요. 

 

그러나 소규모 전투 중심의 FPS는 엔진 특성을 살려 개발 비용을 줄이기 위해 적극 활용을 하려고 하더군요. 하지만 언리얼의 멀티 플레이 기능을 적극 활용하려니 기존 구조의 수정 혹은 모듈 교체의 범위가 애매합니다. 

 

통신 모듈만 바꾸면 괜찮은건지 구조를 좀 수정해야 하는지. 구조 수정은 아주 애매한 문제라서요. 특히, 호스트 역할을 하는 클라이언트 장애시 게임이 중단되니까요. 인터페이스를 그대로 두고 구현부만 고쳐야 하나 어째야 하나 초난감. 

 

H모와 A모(영국산) 게임의 경우는 데디케이트 서버를 게임서버로 돌린다는 소문이 있고 데디케이트 서버 프로세스를 호스트 역할을 하는 클라이언트에서 실행시킨다는 이야기도 들었습니다. 들은 이야기라서 사실 무근일 수도 있습니다. 

 

하여간 그래서 언리얼로 FPS 개발을 해보시거나 진행중인 분들의 경험담을 좀 듣고 싶습니다.

위로

사용자 정보 보기 쪽지 보내기  글 올린이의 웹사이트 방문

 

비회원

손님

 

 

 

 

 

올리기 올려짐: 2007-10-28 20:31

인용과 함께 답변  이 게시물을 del.icio.us에 추가

언리얼 2에서 MMOG가 아닌 MOFPS라면 왠만해선 거의 그대로 쓸수 있습니다. MMOG라면 모듈을 교체하여 구조 수정을 가해야합니다. 구조 수정이라 해봤자 별건 아니고 Engine/Inc,Src,Classes에서 네트웍에 연계된 부분을 새 네트웍 모델에 맞게 수정해주면 됩니다. 

 

언리얼 3에서도 비슷하지만 언리얼 3 엔진이 버전업되면서 MMOG에 대비책을 마련해서 나아지고 있는 실정으로 코드 프레임웍 구조에 많은 손이 안가게 되는 중입니다. 네트웍 자체가 엔진 내부의 다른 모듈들과 크게 엮여있지는 않습니다. 현재 최근 빌드에서는 엔진 자체의 네트웍까지도 좀더 대규모를 소화할수 있게 바뀌어가고 있습니다.

위로

 

비회원

손님

 

 

 

 

 

올리기NAT문제에 대해서는...? 올려짐: 2007-11-07 12:05

인용과 함께 답변  이 게시물을 del.icio.us에 추가

언리얼 엔진에 있는 네트웍 모듈을 그대로 이용하게 된다면 

NAT 이슈는 어떻게 처리하는지 궁금해지네요.. 

 

언리얼3 데모 버젼으로 서버 돌리게 되면 NAT때문에 다른 사람이 

접근 못하는 문제가 발생하는것 같던데.. 

 

이에 대해 아시는 분, 의견좀 부탁드려요.

위로

 

비회원

손님

 

 

 

 

 

올리기Re: NAT문제에 대해서는...? 올려짐: 2007-11-07 22:01

인용과 함께 답변  이 게시물을 del.icio.us에 추가

비회원 씀:

언리얼 엔진에 있는 네트웍 모듈을 그대로 이용하게 된다면 

NAT 이슈는 어떻게 처리하는지 궁금해지네요.. 

 

언리얼3 데모 버젼으로 서버 돌리게 되면 NAT때문에 다른 사람이 

접근 못하는 문제가 발생하는것 같던데.. 

 

이에 대해 아시는 분, 의견좀 부탁드려요.

 

 

당연히 서로 다른 게임들끼리 충돌할까봐 그런게 아닐까요? UDN을 검색해보면 나올겁니다.

 

 

=================================

=================================

=================================

 

 

 

출처: https://wiki.unrealengine.com/TCP_Socket_Listener,_Receive_Binary_Data_From_an_IP/Port_Into_UE4,_(Full_Code_Sample)

 

 

TCP Socket Listener, Receive Binary Data From an IP/Port Into UE4, (Full Code Sample)

Contents

 [hide

Overview

Author: Rama (talk)

Dear Community,

In this tutorial I am giving you the code I used to enable a python script to communicate with UE4 over a TCP socket!

That's right!

I am just straight up giving you my whole source code that I spent the past several hours writing!

Rama

 

 

Build.CS

You will need at least this to work with sockets in UE4

PublicDependencyModuleNames.AddRange(new string[] { 
		"Core", 
		"CoreUObject", 
		"Engine", 
		"InputCore",
 
		"Sockets","Networking"
});

#include <string>

You will also need std::string !

You have to add include line for external symbols after PCH and before corresponding header with source.

example:

// MyClass.cpp
#include "MyProject.h"
#include <string>
#include "MyClass.h"

.h

#include "Networking.h"
 
//AYourClass definition
 
public:
 
FSocket* ListenerSocket;
FSocket* ConnectionSocket;
FIPv4Endpoint RemoteAddressForConnection;
 
bool StartTCPReceiver(
	const FString& YourChosenSocketName,
	const FString& TheIP, 
	const int32 ThePort
);
 
FSocket* CreateTCPConnectionListener(
	const FString& YourChosenSocketName,
	const FString& TheIP, 
	const int32 ThePort, 
	const int32 ReceiveBufferSize = 2*1024*1024
);
 
//Timer functions, could be threads
void TCPConnectionListener(); 	//can thread this eventually
void TCPSocketListener();		//can thread this eventually
 
 
//Format String IP4 to number array
bool FormatIP4ToNumber(const FString& TheIP, uint8 (&Out)[4]);
 
//Rama's StringFromBinaryArray
FString StringFromBinaryArray(const TArray<uint8>& BinaryArray);

.cpp

The flow goes basically from the top down, you can probably guess the purpose of this first function.

 

void AYourClass::Laaaaaauuuunch()
{
                                        //IP = 127.0.0.1, Port = 8890 for my Python test case
	if( ! StartTCPReceiver("RamaSocketListener", "127.0.0.1", 8890))
	{
		//UE_LOG  "TCP Socket Listener Created!"
		return;
	}
 
	//UE_LOG  "TCP Socket Listener Created! Yay!"
}
 
//Rama's Start TCP Receiver
bool AYourClass::StartTCPReceiver(
	const FString& YourChosenSocketName,
	const FString& TheIP, 
	const int32 ThePort
){
	//Rama's CreateTCPConnectionListener
	ListenerSocket = CreateTCPConnectionListener(YourChosenSocketName,TheIP, ThePort);
 
	//Not created?
	if(!ListenerSocket)
	{
		GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("StartTCPReceiver>> Listen socket could not be created! ~> %s %d"), *TheIP, ThePort));
		return false;
	}
 
	//Start the Listener! //thread this eventually
	GetWorldTimerManager().SetTimer(this, 
		&AYourClass::TCPConnectionListener, 0.01, true);	
 
	return true;
}
//Format IP String as Number Parts
bool AYourClass::FormatIP4ToNumber(const FString& TheIP, uint8 (&Out)[4])
{
	//IP Formatting
	TheIP.Replace( TEXT(" "), TEXT("") );
 
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//						   IP 4 Parts
 
	//String Parts
	TArray<FString> Parts;
	TheIP.ParseIntoArray( &Parts, TEXT("."), true );
	if ( Parts.Num() != 4 )
		return false;
 
	//String to Number Parts
	for ( int32 i = 0; i < 4; ++i )
	{
		Out[i] = FCString::Atoi( *Parts[i] );
	}
 
	return true;
}
//Rama's Create TCP Connection Listener
FSocket* AYourClass::CreateTCPConnectionListener(const FString& YourChosenSocketName,const FString& TheIP, const int32 ThePort,const int32 ReceiveBufferSize)
{
	uint8 IP4Nums[4];
	if( ! FormatIP4ToNumber(TheIP, IP4Nums))
	{
		VShow("Invalid IP! Expecting 4 parts separated by .");
		return false;
	}
 
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
	//Create Socket
	FIPv4Endpoint Endpoint(FIPv4Address(IP4Nums[0], IP4Nums[1], IP4Nums[2], IP4Nums[3]), ThePort);
	FSocket* ListenSocket = FTcpSocketBuilder(*YourChosenSocketName)
		.AsReusable()
		.BoundToEndpoint(Endpoint)
		.Listening(8);
 
	//Set Buffer Size
	int32 NewSize = 0;
	ListenSocket->SetReceiveBufferSize(ReceiveBufferSize, NewSize);
 
	//Done!
	return ListenSocket;	
}
//Rama's TCP Connection Listener
void AYourClass::TCPConnectionListener()
{
	//~~~~~~~~~~~~~
	if(!ListenerSocket) return;
	//~~~~~~~~~~~~~
 
	//Remote address
	TSharedRef<FInternetAddr> RemoteAddress = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->CreateInternetAddr();
	bool Pending;
 
	// handle incoming connections
	if (ListenerSocket->HasPendingConnection(Pending) && Pending)
	{
		//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
		//Already have a Connection? destroy previous
		if(ConnectionSocket)
		{
			ConnectionSocket->Close();
			ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->DestroySocket(ConnectionSocket);
		}
		//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
		//New Connection receive!
		ConnectionSocket = ListenerSocket->Accept(*RemoteAddress, TEXT("RamaTCP Received Socket Connection"));
 
		if (ConnectionSocket != NULL)
		{
			//Global cache of current Remote Address
			RemoteAddressForConnection = FIPv4Endpoint(RemoteAddress);
 
			//UE_LOG "Accepted Connection! WOOOHOOOO!!!";
 
			//can thread this too
			GetWorldTimerManager().SetTimer(this, 
				&AYourClass::TCPSocketListener, 0.01, true);	
		}
	}
}
 
//Rama's String From Binary Array
//This function requires 
//		#include <string>
FString AYourClass::StringFromBinaryArray(const TArray<uint8>& BinaryArray)
{
	//Create a string from a byte array!
	std::string cstr( reinterpret_cast<const char*>(BinaryArray.GetData()), BinaryArray.Num() );
	return FString(cstr.c_str());
}
 
//Rama's TCP Socket Listener
void AYourClass::TCPSocketListener()
{
	//~~~~~~~~~~~~~
	if(!ConnectionSocket) return;
	//~~~~~~~~~~~~~
 
 
	//Binary Array!
	TArray<uint8> ReceivedData;
 
	uint32 Size;
	while (ConnectionSocket->HasPendingData(Size))
	{
		ReceivedData.Init(FMath::Min(Size, 65507u));
 
		int32 Read = 0;
		ConnectionSocket->Recv(ReceivedData.GetData(), ReceivedData.Num(), Read);
 
		//GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("Data Read! %d"), ReceivedData.Num()));
	}
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
	if(ReceivedData.Num() <= 0)
	{
		//No Data Received
		return;
	}
 
	VShow("Total Data read!", ReceivedData.Num() );
	GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("Data Bytes Read ~> %d"), ReceivedData.Num()));
 
 
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	//						Rama's String From Binary Array
	const FString ReceivedUE4String = StringFromBinaryArray(ReceivedData);
	//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
 
 
	VShow("As String!!!!! ~>",ReceivedUE4String);	
	GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("As String Data ~> %s"), *ReceivedUE4String));
}

Core Research I Am Sharing with You

The hardest part of this whole process for me was converting the received binary data into UE4's FString format!

I wrote this function to do it, which adds the null terminator and everything, and uses the strong backbone of std::string!

//Rama's String From Binary Array
//This function requires 
//		#include <string>
FString AYourClass::StringFromBinaryArray(const TArray<uint8>& BinaryArray)
{
	//Create a string from a byte array!
	const std::string cstr( reinterpret_cast<const char*>(BinaryArray.GetData()), BinaryArray.Num() );
 
	//FString can take in the c_str() of a std::string
	return FString(cstr.c_str());
}

 

It is surprisingly succinct but believe you me it took me hours to figure out this very concise function.

I hope you get to make use of it!

)

How It Works

The first socket listens on the port and IP supplied, and if a connection is received on this port, then the actual ListenerSocket is created.

The ListenerSocket is run in very short looping timer of 0.01 seconds.

You could also use a thread for this :)


Rama's Tutorial on Multi-Threading, Create Threads in UE4


Whenever the ListenerSocket receives data, it makes sure to gather all of it using the while loop, and then I convert the results into a FString.

/Binary Array!
TArray<uint8> ReceivedData;
 
uint32 Size;
while (ConnectionSocket->HasPendingData(Size))
{
	ReceivedData.Init(FMath::Min(Size, 65507u));
 
	int32 Read = 0;
	ConnectionSocket->Recv(ReceivedData.GetData(), ReceivedData.Num(), Read);
 
	//GEngine->AddOnScreenDebugMessage(-1, 5.f, FColor::Red, FString::Printf(TEXT("Data Read! %d"), ReceivedData.Num()));
}

 

If you are not receiving string data you can skip that part and just pass out the binary array itself :)

Another TCP Source Code, by Alfalfasprossen

Community member AlfalfaProssen is generously sharing his own ongoing TCP plugn, check back over time to see how it is developing!

Thanks Alfalfasprossen!

Alfalfa's TCP Plugin

Conclusion

I am sharing my last several hours of research with you in fully functional C++ code format!

Enjoy!

Rama (talk)

Category

 

 

 

반응형

 

 

728x90

 

 

=================================

=================================

=================================

 

 

 

출처: https://wiki.unrealengine.com/TCP_Socket_Listener,_Receive_Binary_Data_From_an_IP/Port_Into_UE4,_(Full_Code_Sample)

 

 

Third Party Socket Server Connection

Rate this Article:

5.00

 (2 votes)

Approved for Versions:(please verify)

We’ve been quietly working on our new game here at OSnap! Games and one of the features our new game will include is a lobby system where all players can chat among one another. The UE4 dedicated server is great for a game server but it’s overkill for something as simple as a chat server so we set out to get UE4 connecting to a third party socket server.

Contents

 [hide

Creating the Socket

The first step in getting UE4 connected to a third party server is initializing a socket.

 

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

 

The parameters are as follows

  1. Type
  2. Description
  3. ForceUDP

  In our case we're connecting using TCP so we've set ForceUDP to false.

 

Preparing the Address

The next part is getting the address you wish to connect to ready. Epic provides the tools to get this done quickly.

FString address = TEXT("127.0.0.1"); int32 port = 19834; FIPv4Address ip; FIPv4Address::Parse(address, ip); TSharedRef addr = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->CreateInternetAddr(); addr->SetIp(ip.GetValue()); addr->SetPort(port);

 

Now that your address is ready to go you simply have to tell UE4 to start the connection.

 

bool connected = Socket->Connect(*addr);

If connected is true you've successfully connected to your socket server!

 

Sending a Message

Alright, so you're connected but how do you send messages to it? A lot of that is up to you. Depending on your server there are different ways to serialize and send a message. The important part though is how does UE4 handle it.

First things first, we must prepare the message to be sent.

FString serialized = TEXT("loadPlayer|1"); TCHAR *serializedChar = serialized.GetCharArray().GetData(); int32 size = FCString::Strlen(serializedChar); int32 sent = 0;

 

What's going on in the above? We're sending a message to a socket server with the type "loadPlayer" and a single parameter of 1. What is happening in UE4 here is we're taking an FString, and turning it into a TCHAR*.

Finally, with the message formatted we can send it to our server!

 

bool successful = Socket->Send((uint8*)TCHAR_TO_UTF8(serializedChar), size, sent);

 

Sending data in UE4 requires it to be a uint8* and again, Epic provides the tools to get from TCHAR* to UTF8 which can be sent as a uint8*.

As far as reading data back from your socket server the key is in the functions HasPendingData and Recv of the FSocket class.

 

Dependency in Build.cs

One final thing to take note of. Inside your project's Build.cs file you'll need to add the "Sockets" package as a dependency in PublicDependencyModuleNames.

 

PublicDependencyModuleNames.AddRange( new string[] { "Core", "CoreUObject", "Engine", "Sockets" } );

Reposted from http://www.osnapgames.com/2014/05/24/connecting-to-a-third-party-socket-server-in-unreal-engine-4/

 

 

=================================

=================================

=================================

 

 

 

출처: http://www.osnapgames.com/2014/05/24/connecting-to-a-third-party-socket-server-in-unreal-engine-4/

 

 

Connecting to a Third Party Socket Server in Unreal Engine 4

 
We’ve been quietly working on our new game here at OSnap! Games and we’ve selected to build it using Unreal Engine 4.

One of the features our new game will include is a lobby system where all players can chat among one another. The UE4 dedicated server is great for a game server but it’s overkill for something as simple as a chat server so we set out to get UE4 connecting to a third party socket server. Luckily the developers at Epic have provided the tools to do just this!

 

Creating the Socket

The first step in getting UE4 connected to a third party server is initializing a socket.

 

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

 

The parameters are as follows

  1. Type
  2. Description
  3. ForceUDP

In our case we’re connecting using TCP so we’ve set ForceUDP to false.

 

Preparing the Address

The next part is getting the address you wish to connect to ready. Again, Epic provides the tools to get this done quickly.

FString address = TEXT("127.0.0.1"); int32 port = 19834; FIPv4Address ip; FIPv4Address::Parse(address, ip); TSharedRef addr = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSTEM)->CreateInternetAddr(); addr->SetIp(ip.GetValue()); addr->SetPort(port);

 

Now that your address is ready to go you simply have to tell UE4 to start the connection.

 

bool connected = Socket->Connect(*addr);

If connected is true you’ve successfully connected to your socket server!

 

Sending a Message

Alright, so you’re connected but how do you send messages to it? A lot of that is up to you. Depending on your server there are different ways to serialize and send a message. The important part though is how does UE4 handle it.

First things first, we must prepare the message to be sent.

FString serialized = TEXT("loadPlayer|1"); TCHAR *serializedChar = serialized.GetCharArray().GetData(); int32 size = FCString::Strlen(serializedChar); int32 sent = 0;

 

What’s going on in the above? We’re sending a message to a socket server with the type “loadPlayer” and a single parameter of 1. What is happening in UE4 here is we’re taking an FString, and turning it into a TCHAR*.

Finally, with the message formatted we can send it to our server!

 

bool successful = Socket->Send((uint8*)TCHAR_TO_UTF8(serializedChar), size, sent);

 

Sending data in UE4 requires it to be a uint8* and again, Epic provides the tools to get from TCHAR* to UTF8 which can be sent as a uint8*.

As far as reading data back from your socket server the key is in the functions HasPendingData and Recv of the FSocket class.

 

Dependency in Build.cs

One final thing to take note of. Inside your project’s Build.cs file you’ll need to add the “Sockets” package as a dependency in PublicDependencyModuleNames.

 

PublicDependencyModuleNames.AddRange( new string[] { "Core", "CoreUObject", "Engine", "Sockets" } );

 

 

 

 

=================================

=================================

=================================

 

 

 

출처: https://answers.unrealengine.com/questions/20265/connecting-to-socket-server.html

 

Connecting to Socket Server

I've done what reading I can in the documentation so far, and I believe I'm on the right track but perhaps someone can correct me.
I'm attempting to connect to a custom socket server rather than a dedicated server run by players.
From my understanding doing this would involve FSocket, ISocketSubsystem, and FInternetAddr.
So far I've attempted to compile the following.
FSocket *socket = ISocketSubsystem::Get()->CreateSocket("default", "default", false);
Now I understand why this isn't working, because ISocketSubsystem is an interface. What class implements this interface? How should I be using these classes? Has anyone done anything like this yet, or attempted to?
Product Version: Not Selected

Tags:unreal engine 4c++networkingmultiplayerfsocket
more ▼
asked Mar 28 '14 at 1:22 PM
overlawled 
171  18  10  25

2 answers:sort voted first 

ISocketSubsystem::Get() returns a singleton for the running platform's socket subsystem. It is this singleton that implements the ISocketSubsystem interface, which is why your example code works. You will likely stumble upon this pattern in other places as well.
In the Networking module there are two helper classes, FTcpSocketBuilder and FTcpListener, for TCP clients and servers respectively. Please note that this module is currently not documented, and the API may change in the future, so use it with care. At the very least, it will provide you with some examples on how to create sockets in UE4. Look at FTcpSocketBuilder::Build() to see what it is doing. The module also contains helper classes for UDP sockets.
In particular, note that, after creating a socket you will also have to bind to a port and possibly perform other initialization steps in order to establish a connection to your server.
more ▼
answered Mar 29 '14 at 12:18 AM
gmpreussner STAFF 
2.7k  78  23  115

 overlawled Mar 29 '14 at 2:32 AM


When I use ISocketSubsystem::Get() I get a linker error.
Looking at the FTcpSocketBuilder class I have a few questions you can hopefully answer.
  • Do I need to define the BoundToAddress, and BoundToEndPoint?
  • Does the port it's bound to on the client need to match the port the server is using?
  • Is there anything that absolutely needs to be defined in that class before building the socket?
 overlawled Mar 29 '14 at 7:47 AM
1
Solved my linker error, missing "Sockets" in my dependency module.
 Superdolgu Feb 27 '15 at 5:59 PM Newest


valla helal lan
 Dave4723 Apr 09 '14 at 7:35 PM


Could you tell me what you mean by dependency module?
i'm getting linker errors with the ISocketSubSystem...
 overlawled Apr 12 '14 at 12:06 PM


In PROJECTNAME.Build.cs you need to add "Sockets" to PublicDependencyModuleNames
You're better off creating it that way (assuming TCP):
FSocket *socket = ISocketSubsystem::Get(PLATFORM_SOCKETSUBSYSSTEM)->CreateSocket(NAME_Stream, TEXT("My server socket"), false);
There's a number of socket subsystem in the engine and more than one can be present at a time, so providing PLATFORM_SOCKETSUBSYSTEM is safer.
more ▼
answered Mar 29 '14 at 12:23 AM
RCL STAFF 
1.4k  37  6  48

 RCL STAFF Mar 29 '14 at 12:28 AM


Nevermind, builder approach suggest by Max is cleaner, however you can still use that code if you need to know the guts.

 

 

 

=================================

=================================

=================================

 

 

 


출처: http://cafe.naver.com/unrealenginekr/11053

C++ IOCP Server + EventSelect Client 언리얼 통신

 

 

한 이틀 삽질해보니 잘 되네요.

간단한 채팅 정도 구현했습니다. 확실히 Unity3D 하다가 해보니 뭔가 해냈을때 뿌듯함이 있어요 -0 -;;

 

 일단 학생이라 졸작으로 서버 포함한 게임 제작을 목표로 하고 있는데, 언리얼 네트워크 기능을 하나도 안쓰려고하니 패킷 설계를 어떻게 해야할지 감이 안잡히네요. 혹.. 온라인 RPG 관련해서 패킷 설계 해보신 경험담 있으신분 계신가요?

(로그인 로비 정도는 쉬운데, 역시 메인 게임에서 클라이언트의 담당할 부분과 서버는 패킷을 받아 어느 정도만큼 게임을 처리하는 부분을 나누는게 감이 안오네요.)

 

 

 

 

  • 멋지시네요~ ^^
  •   뼈로그래머
    2016.08.12. 11:12답글가..감사합니다
  • 신고
  •   Ocelot
    2016.08.12. 00:07답글굉장하네요

    컴퓨터 공학 전공이신가요?
  • 신고
  •   뼈로그래머
    2016.08.12. 11:12답글넴 게임 관련 전공입니다
  • 신고
  •   Ocelot
    2016.08.12. 11:29답글뼈로그래머 게임 학과인가요? 컴퓨터 공학인데 게임쪽 과정이 있는건가요?
  • 신고
  •   뼈로그래머
    2016.08.12. 11:31답글Ocelot 게임소프트웨어공학과입니다.
  • 신고
  •   Ocelot
    2016.08.12. 11:36답글뼈로그래머 학과에서 가르치나요? 아니면 혼자 공부하셔서 구현하신건가요?
  • 신고
  •   뼈로그래머
    2016.08.12. 11:41답글Ocelot 쪽지로 드릴게요
  • 신고
  •   나가놀자
    2016.08.12. 00:16답글서버 프로그래머는 아닙니다만, 원리는 간단합니다.
    유저에게 노출되지 말아야 할 연산은 서버에서 처리해야 됩니다.
    이를 테면, 아이템 드랍이나 몬스터에게 데미지를 입히는 것 등이 있겠죠.
    (리버싱 능력이 있어야 겠지만) 클라이언트 코드는 유저가 모두 볼 수 있고 변조할 수도 있습니다.
    만약 아이템 드랍이, 유저 즉 클라이언트로 넘어가게 되면 
    유저가 클라이언트를 변조해서 원하는 아이템을 드랍시킬 수 있을 것입니다.
    데미지도 같은 맥락입니다. 이른바 데미지 핵을 만들기가 매우 수월해집니다.
  • 신고
  •   뼈로그래머
    2016.08.12. 11:13답글아.. 그럼 플레이어의 입력을 보내서 서버에서 좌표를 계산하나요?
    아니면 좌표를 보내는데, 비이상적인 상태는 서버에서 감지해야하나요?
    (예 : 갑자기 10미터 이동)

    또 다른 유저 정보 같은 경우에는 좌표, 방향, 애니메이션 상태(걷기, 뛰기 등)을 보내서
    받은 쪽에서 처리하는 건가요?

    말씀하신대로 일단은 거의 엔진은 렌더러 느낌으로 제작하려고 합니다만
    AI 길찾기 같은 기능(Navigation Mesh 등)은.. 언리얼에서 진행해야하는지
    서버에서 따로 지형정보를 가지고 자체적인 길찾기로 처리해야하는지도 궁금합니다
  • 신고
  •   나가놀자
    2016.08.12. 11:00답글뼈로그래머 숨겨야 할 것도 있겠지만 서버 부하도 고려해야 겠지요.
    이동은 연산량이 많습니다. 
    말씀하신 것처럼 결과값으로 이동 핵 같은 걸 쓰는지 감시하면 됩니다.
    물론 서버가 스펙이 좋고 클라이언트가 적은데다 굉장히 중요한 연산이라면 서버가 해도 됩니다.
  • 신고
  •   뼈로그래머
    2016.08.12. 11:13답글나가놀자 서버로 쓰고 있는 컴퓨터가 남는 부품 이리저리 결합한거라 서버에 부담이 적게가도록
    짜봐야겠네요 일단 공부삼아 기본적인 MMO 환경 구성한 뒤에 후기 남겨보겠습니다.
  • 신고
  •   나가놀자
    2016.08.12. 11:06답글뼈로그래머 이동은 조작감과도 연관되니 서버로 옮기는 것은 되도록 피하세요.
    남의 캐릭터의 위치가 튀는 건 쉽게 넘어 가지만
    내 캐릭터의 위치가 튀는 건 굉장히 신경쓰이고 짜증날 수 있습니다.
  • 신고
  •   ihopi
    2016.08.12. 10:07답글네비게이션에 대해서는 이 문서를 참조 해 보세요.
    https://docs.unrealengine.com/latest/KOR/Resources/ContentExamples/NavMesh/index.html


    일단 졸업작품이라고 하셨으니, 리버싱에 대한 걱정은 하지 않는게 좋을 듯 합니다.
    고로.. 최대한 간단한 구현에 중점을 두고 작업을 하면 될 것 같습니다.
    즉, 서버에서 해야 할 일과, 클라이언트에서 해야 할 일을 정리하신 후, 주고받을 프로토콜을 최대한 간결하게 작성하시면 되겠습니다.

    서버에는 유저에 대한 모든 정보가 저장되어져 있고, 이동시에는 좌표만 주고받게 되겠죠.
    예를 들면 신규 유져가 반경에 나타났을 경우, 해당 유저의 정보를 전달받게 되고, 이후 해당 유저의 이동좌표만 전달받으면 클라이언트 내에서 다른 유저가 움직이게 되는 것이 보이는 것 처럼 말이죠.

    실제 작업하신 내용을 보니 사실, 이런 조언이 필요 없을 것 같긴 합니다만... ㅋ
    예전 IOCP 서버 작업 한 이후로 두번다시 손대지 말아야지 했는데, 학생분이신데 구현하신 거 보니 왠지 제가 챙피하기도 하네요.
  • 신고
  •   뼈로그래머
    2016.08.12. 12:54답글방학겸, 인턴하는겸해서 서버랑 언리얼 공부를 병행하고 있는데 
    따로 따로 공부한게 서로 붙으니까 더 재밌어지는것 같습니다.
    원래는 따로 DX로 Unity 구조 본따 만든 자체 엔진을 쓰려고 했는데,
    역시.. 이쁘지가 않아서 따로 봉인해두었습니다.

    유저 정보는 따로 MySQL DB 서버를 구축해두었고 서버 종류는
    로그인 서버(DB 서버), 단일 서버, 채널(다수)로 구성해보려고 하고 있어요.

    P.S 요새는 좋은 책이 많아서요.. IOCP는 자료가 많이 없어서 절판된책 구해구해 보고 있습니다.
    사실.. C# 서버, Web 서버 종류가 많아서 C++로 IOCP 같은 오래된 기술(?)을 보고 있는게 좋은 건지 아직 모르겠습니다. 네트워크는.. 간단한 예제하하는 데에도 기본기가 많이 필요해서 봐도 봐도 다시봐야하는 부분인것 같아요.
  • 신고
  •   알파카
    2016.08.12. 12:43답글클라이언트 수가 많지 않다면 서버도 언리얼 엔진으로 작업하는 것이 가장 안정적일 것 같아요. 
    다만 패킷을 추가하려면 엔진 코드를 수정해야 합니다. 
    언리얼은 서버/클라이언트 통신을 할 때 udp로 통신하고 있습니다. 
    하나의 udp 소켓에 ControlChannel/ActorChannel/VoiceChannel로 구분해서 통신을 하도록 
    설계되어 있습니다. 게임내의 액션은 ActorChannel에서 담당하고 있어요.

    ControlChannel : Connection control.
    ActorChannel : Actor-update channel.
    VoiceChannel : VoIP data channel

    네트워크 프로그래밍을 공부 중이시라면 엔진의 아래 코드를 보는 것을 추천합니다.

    Engine\Source\Runtime\Sockets
    Engine\Source\Runtime\Engine\Public\Net
  • 신고
  •   뼈로그래머
    2016.08.16. 10:19답글연휴 여행다녀오느라 댓글을 늦게달았네요 ㅠㅠ
    말씀해보신 부분 참고해보겠습니다.
  • 신고
  • 삭제된 댓글입니다.
  •   뼈로그래머
    2016.08.16. 10:20답글감사합니다. 화이팅!
  • 신고
  •   송쩡이
    2016.08.16. 18:32답글대단하시네요 ㅜㅜ 채팅구현에 저는 애먹고 있습니다 ㅜ ㅜ 
    채팅 하는 클라부분 공유 가능한가여 ㅜㅜ
  • 신고
  •   뼈로그래머
    2016.08.21. 14:16답글최근에 시간이 없어서 못하고있네요 ㅠ..
    정리해서 한번 자료올리겠습니다.
  • 신고

 

 

 

 

 

=================================

=================================

=================================

 

 

 

 

출처: http://cafe.naver.com/unrealenginekr/11812

 

제가 지금 TCP/IP 프로그래밍 배우고있는데요

 

제가 언리얼 네트워크게임을 만들어야 하는데 네트워크가 어떤식으로 동작하는건가요?

 

엔진 자체에 네트워킹 기능이 있어서 정말 쉽게 쓸수있다는데 맞나요?? 그리고 어떻게 쓰는건가요..?

 

클라는 기껏해봐야 최대 4인정도 플레이할 수 있는 FPS 게임을 만들려고 합니다.

 

막 IOCP로 서버 만들어서 해야되고 그런건 없나요?

 

 

  • TCP보다 더 고급 프로토콜이 이미 구성되어 있습니다.
    리플리케이션을 검색하세요.
  •   런던왕
    2016.10.08. 21:16답글이미 구성되어있다는 말이 무슨말인지 모르겠습니다.. 따로서버구현할 필요가없다는 뜻인가요?
  • 신고
  •   나가놀자
    2016.10.08. 21:35답글런던왕 https://docs.unrealengine.com/latest/KOR/Gameplay/Networking/index.html
    조건에 부합한다면 윈속 등 소켓 API를 전혀 쓰지 않고 멀티 게임 제작이 가능합니다.
  • 신고
  •   라면조아
    2016.10.09. 20:22답글라이브러리에 건슬링거 예제나 카우치 나이트 예제를 한번보시면 네트워크 기반으로 제작 되어있어서 언리얼에 대해 어느정도 아신다면 금방 이해하실수 있을거예요
  • 신고

 

 

 

 

=================================

=================================

=================================

 

 

 

 

 

출처: http://cafe.naver.com/unrealenginekr/9761

 

게임서버를 공부하고있는 학생입니다.

 

언리얼에서 c++ 클라로 게임을 만들어서

 

제가 제작한 임의의 서버를 연결한 네트워크 게임을 만들려고 하는데

검색해보면 전부 언리얼에서 제작해둔 서버를 사용하는거같더라구요..

 

따로 만든 IOCP나 TCP 서버와 연결하려고하면 


그냥 DirectX 나 C++ 클라이언트처럼 연동을 하면 되는건가요?

 

이부분이 확실하지 않아서.. 작업을 미뤄두고있는 상태라.. 

 

고수님들의 조언좀 부탁드립니다!!

 

 

 

(클라 측에서는)

언리얼에는  TCPLink 라는 클래스가 있습니다.  플랫폼에 무관하게 네트워킹 작업을 수행할 수 있게 Socket 를 wrapping 한 것으로 알고 있습니다.

 

일반적인 socket programming 에 대한 개념을 알고 있으면 쉽게 사용 가능할 것 같습니다.

 

(서버측에서는)

이전에  PC 온라인 게임 제작할 때와 같다고 생각하면 됩니다. 웹서버 방식으로 동작하는 게임 서버도 최근에는 많이 있긴한데, 이는 서버단에 로직을 구동하기가 쉽지 않습니다. 서버 로직을 구동하려면 자체 서버를 제작하는 것이 편할 겁니다.

 

최근 모바일 게임 서버도 일반적인 (이전과 같은) 온라인 게임 서버와 같은 방식으로 구동되고 있다고 생각하면 됩니다. 

 

  •  
  • 감사합니다~ 좀더 찾아보고 구현해야겠네요 ㅎ
2016.05.25. 00:24

네, 기존 C++ 라이브러리 연동하듯이 하시면 됩니다.

참고로, 프라우드넷의 C++ 라이브러리도 연동할 수 있습니다. 프라우드넷의 경우 Windows 뿐만 아니라 안드로이드,아이폰용 라이브러리도 같이 지원되므로, 멀티플랫폼 개발을 고려하시면 좋은 참고가 될겁니다.

 

언리얼엔진4에 프라우드넷 붙여 쓰는 방법 문서 링크 

 

  •   Ruthless
    오오.. 넷텐션 대표님..
    혹시 프라우드넷을 적용한 UE4 샘플 프로젝트가 있을까요?

    정말 적용해보고 싶긴 한데 어느 단계부터 구현해야 될지 좀 막막해서요.
    https://docs.unrealengine.com/latest/KOR/Gameplay/Networking/Actors/index.html
    언리얼에서 기존에 지원하는 리플리케이션 기능을 사용하지 않고 프라우드넷에서 제공하는 것을 사용하여 만들어야 하는지도 궁금합니다.
  •   kalsbold
    좋은정보 감사합니다 ㅎㅎ 하지만 제가 서버 전공중인 학생이라 제가 직접 만든 서버로 연동을 해야되서요 ㅎㅎ

 

 

=================================

=================================

=================================

 

 

반응형
그리드형


관련글 더보기

댓글 영역