반응형

using System; //For String, Int32, Console
using System.Text; //For Encoding
using System.Net; //For IPEndPoint
using System.Net.Sockets; //For UdpClient, SocketException

class UdpEchoClient
{
    static void Main(string[] args)
    {
        String server = "127.0.0.1";
        int servPort = 9100;

        //Convert input String to an array of bytes
        byte[] sendPacket = Encoding.ASCII.GetBytes("UDP Client Test!!!");//네트워크 데이타 송수신은 기본적으로 바이트 데이타를 사용하는데,
                                                                          //따라서 문자열을 보낼 경우 먼저 바이트로 인코딩한 후 보내게 된다.
                                                                          //보통 일반 영문은 ASCII로 인코딩하고, 한글 등 비영문 문자열은 UTF 인코딩을 사용한다.

        //Create a UdpClient instance
        UdpClient client = new UdpClient();

        try
        {
            //Send the echo string to the specified host and port
            client.Send(sendPacket, sendPacket.Length, server, servPort);//UdpClient 객체의 Send() 메서드를 사용하여 데이터(UDP에서 datagram 이라 함)를 서버로 보낸다. 

            Console.WriteLine("Sent {0} bytes to the server...", sendPacket.Length);

            //This IPEndPoint instance will be populated with the remote sender`s
            //endpoint information after the Receive() call
            IPEndPoint remoteIPEndPoint = new IPEndPoint(IPAddress.Any, 0);//IPEndPoint 클래스에는 호스트의 IP주소와 포트번호등의 정보를 가지고 있고 이를 통해 호스트 서버에 연결 지점을 형성함.
                                                                           //로컬주소를 바인드하거나 소켓과 원격주소를 연결하는데 사용

            //Attempt echo reply receive() call
            byte[] rcvPacket = client.Receive(ref remoteIPEndPoint);//UDP에서 데이타를 수신할 경우는 UdpClient 객체의 Receive() 메서드를 사용한다.
                                                                    //Receive() 메서드는 특히 수신 데이타와 함께 상대 컴퓨터의 종단점(IP주소와 포트) 정보도 같이 전달받는데,
                                                                    //이를 위해 IPEndPoint 객체를 ref 파라미터로 전달한다.
                                                                    //이를 통해 데이타가 수신되면 누가 그 데이타를 전송했는지 알 수 있다.
                                                                    //TCP와 달리 UDP는 Connectionless 프로토콜이기 때문에 이렇게 누가 보낸 데이타인지를 알 필요가 있다.

            Console.WriteLine("Received {0} bytes from {1}:{2}", rcvPacket.Length, remoteIPEndPoint, Encoding.ASCII.GetString(rcvPacket, 0, rcvPacket.Length));
        }
        catch (SocketException se)
        {
            Console.WriteLine(se.ErrorCode + ": " + se.Message);
        }

        client.Close();
    }
}

반응형