본문 바로가기
C#

[C#] UDP Socket을 이용한 통신

by Jcoder 2020. 12. 4.

서버와 클라이언트

UDP 참고 : UDP - 나무위키 (namu.wiki) 

 

UDP - 나무위키

데이터 신뢰성 문제가 있는 프로토콜이라 우스갯소리로 Unreliable Damn Protocol(믿지 못할 빌어먹을 프로토콜)의 축약어라 부르는 경우도 있다. UDP라는 독자적인 규약으로 떨어져 나오긴 했으나 사

namu.wiki

 

1. 서버

class Program

{

    static void Main(string[] args)

    {

        Console.WriteLine("UDP Server");

        ServerFunc();

    }

 

    private static void ServerFunc()

    {

        // IPv4, 스트림, TCP --> TCP는 스트림으로, UDP는 데이터그램으로

        using (Socket svrSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))

        {

        // 어떤 ip이던 9999 포트로 --> 0.0.0.0:9999

        IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 9999);

 

        svrSocket.Bind(endPoint);

 

        byte[] recvBytes = new byte[1024];

        EndPoint cltEP = new IPEndPoint(IPAddress.None, 0);

 

        while (true)

        {

            int nRecv = svrSocket.ReceiveFrom(recvBytes, ref cltEP); // 받은 문자 바이트

            string text = Encoding.UTF8.GetString(recvBytes, 0, nRecv);

 

            Console.WriteLine(text);

 

            byte[] sendBytes = Encoding.UTF8.GetBytes("Hello: " + text); // 전송

 

            svrSocket.SendTo(sendBytes, cltEP);

        }

        }

    }

}

 

2. 클라이언트

class Program

{

    static void Main(string[] args)

    {

        Console.WriteLine("UDP Client");

        ClientFunc();

    }

 

    private static void ClientFunc()

    {

        using (Socket cltSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))

        {

            EndPoint ServerPoint = new IPEndPoint(IPAddress.Loopback, 9999);

            EndPoint SendPoint = new IPEndPoint(IPAddress.None, 0);

 

            byte[] sendByte = Encoding.UTF8.GetBytes("I'm udp client");

 

            cltSocket.SendTo(sendByte,ServerPoint);

 

            byte[] recvBytes = new byte[1024];

            int nRecv = cltSocket.ReceiveFrom(recvBytes, ref SendPoint);

 

            string text = Encoding.UTF8.GetString(recvBytes, 0, nRecv);

            Console.WriteLine(text);

            cltSocket.Close(); // 세션 종료

        }

    }

}