Unity NetworkConnection 클래스 설명
개요
NetworkConnection 클래스는 Unity의 고수준 API로, 네트워크 연결을 관리합니다. 이 클래스는 NetworkClient 및 NetworkServer와 관련이 있으며, 각 연결에 대한 세부 정보를 캡슐화합니다. UNet은 이제 지원이 중단되었으므로, 새로운 솔루션인 게임 오브젝트용 넷코드로 전환하는 것이 권장됩니다.
주요 프로퍼티
NetworkConnection 클래스는 다음과 같은 주요 프로퍼티를 포함합니다:
| 프로퍼티 이름 | 설명 |
|---|---|
| hostId | 연결의 NetworkTransport hostId |
| connectionId | 연결의 NetworkTransport connectionId |
| isReady | 연결로 상태 업데이트를 전송할지 제어하는 플래그 |
| lastMessageTime | 연결에서 메시지가 마지막으로 수신된 시간 |
| address | 연결된 엔드포인트의 IP 주소 |
| playerControllers | AddPlayer()를 사용하여 추가된 플레이어 집합 |
| clientOwnedObjects | 연결이 권한을 보유한 오브젝트 집합 |
중요 메서드
이 클래스는 데이터 전송 및 수신 시 호출되는 가상 메서드를 제공합니다. 이 메서드를 통해 특정 데이터 패킷을 검사하거나 수정할 수 있습니다. 아래는 주요 메서드의 기본 예제입니다.
public virtual void TransportRecieve(byte[] bytes, int numBytes, int channelId)
{
HandleBytes(bytes, numBytes, channelId);
}
public virtual bool TransportSend(byte[] bytes, int numBytes, int channelId, out byte error)
{
return NetworkTransport.Send(hostId, connectionId, channelId, bytes, numBytes, out error);
}
위의 메서드는 각각 수신된 데이터와 전송할 데이터를 처리하는 기본 동작을 정의합니다.
커스터마이즈된 클래스 예제
아래는 NetworkConnection에서 상속된 DebugConnection 클래스의 예입니다. 이 클래스는 수신 및 전송 패킷의 내용을 콘솔에 기록합니다.
class DebugConnection : NetworkConnection
{
public override void TransportRecieve(byte[] bytes, int numBytes, int channelId)
{
StringBuilder msg = new StringBuilder();
for (int i = 0; i < numBytes; i++)
{
var s = String.Format("{0:X2}", bytes[i]);
msg.Append(s);
if (i > 50) break;
}
UnityEngine.Debug.Log("TransportRecieve h:" + hostId + " con:" + connectionId + " bytes:" + numBytes + " " + msg);
HandleBytes(bytes, numBytes, channelId);
}
public override bool TransportSend(byte[] bytes, int numBytes, int channelId, out byte error)
{
StringBuilder msg = new StringBuilder();
for (int i = 0; i < numBytes; i++)
{
var s = String.Format("{0:X2}", bytes[i]);
msg.Append(s);
if (i > 50) break;
}
UnityEngine.Debug.Log("TransportSend h:" + hostId + " con:" + connectionId + " bytes:" + numBytes + " " + msg);
return NetworkTransport.Send(hostId, connectionId, channelId, bytes, numBytes, out error);
}
}
이 DebugConnection 클래스는 패킷의 첫 50바이트를 표시하며, 디버깅을 위한 유용한 정보를 제공합니다. 이 클래스를 사용하려면 NetworkClient 또는 NetworkServer에서 SetNetworkConnectionClass() 함수를 호출해야 합니다.
요약
NetworkConnection은 Unity의 네트워크 기능을 활용하기 위한 주요 클래스입니다. 이 클래스를 통해 다양한 멀티플레이어 게임의 네트워크 통신을 효율적으로 관리할 수 있습니다. Unity의 최신 네트워크 솔루션을 통해 더욱 향상된 멀티플레이어 경험을 제공할 수 있습니다.