C# 을 이용한 간단한 UDP서버와 UDP클라이언트 사용

2022. 3. 30. 21:18Unity

네트워크 강의 같은 걸 들어봤다면 TCP는 전송을 보장하지만 속도가 느리고 UDP는 전송을 보장하지 않는 대신 속도가 빠르다는 얘기는 한번쯤은 들어봤을 것이다.

아마 스타크래프트의 랜 멀티플레이 어쩌구 하면서 들었던 기억이 있느데 그래서 간단하게 UDP 서버를 생성하고 클라이언트에서 서버로 메시지를 보내보려한다.

 

using System;
using System.Net;
using System.Net.Sockets;

// 1. UdpClient 객체 생성, 포트 7777에서 Listening
UdpClient srv = new UdpClient(7777);

// 클라이언트 IP를 담을 변수
IPEndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0); ;

while (true)
{
    // 2. 데이터 수신
    byte[] dgram = srv.Receive(ref remoteEP);
    Console.WriteLine("[Receive] {0} 로부터 {1} 바이트 수신", remoteEP.ToString(), dgram.Length);

    // 3. 데이터 송신
    srv.Send(dgram, dgram.Length, remoteEP);
    Console.WriteLine("[Send] {0}로 {1} 바이트 송신", remoteEP.ToString(), dgram.Length);
}

이건 유니티에서 생성한 스크립트가 아닌 비주얼 스튜디오에서 작성한 코드이다. 그래도 뭔가 이상하게 생겼다면 .NET 6.0버전이라 메인 함수가 없어서 그렇게 느껴지는 것일 거다.

 

어쨌든 이 코드를 실행하면

 

이렇게 빈 콘솔창이 뜬다.

 

이 상태에서 유니티에서

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using static System.Console;

public class UDP_client : MonoBehaviour
{
    // 1. Udp client 객체 생성
    UdpClient cli = new UdpClient();

    string msg = "안녕하세요";

    
    // Start is called before the first frame update
    void Start()
    {
        byte[] datagram = Encoding.UTF8.GetBytes(msg);

        // 2. 데이터 송신
        cli.Send(datagram, datagram.Length, "127.0.0.1", 7777);
        Debug.Log("[Send] 127.0.0.1:7777로 "+ datagram.Length + "바이트 전송");

        // 3. 데이터 수신
        IPEndPoint epRemote = new IPEndPoint(IPAddress.Any, 0);
        byte[] bytes = cli.Receive(ref epRemote);
        Debug.Log("[Receive] "+ epRemote.ToString() + "로부터" + bytes.Length +"바이트 수신");

        // 4. UdpClient 객체 닫기
        cli.Close();
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

이렇게 클라이언트를 생성하여 빈 오브젝트에 붙여주고 실행하면...

 

이렇게 성공적으로 송수신을 하게 된다.