블로그 이미지
따시쿵

calendar

1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31

Notice

2015. 2. 12. 15:57 C# with UDP/IP

udp multicast 는 sender가 receiver 에게 데이타를 단방향 통신으로 전달하는 기술 기법입니다.


multicast 구현시 고려할 사항


▷ IP multicast 에서 사용할 아이피를 적당하게 잘 선택해야 합니다. 

   선택한 아이피로 멀티캐스트그룹을 만들어야 하므로 다른 시스템에서 사용하지 않는 아이피를 사용

   합니다.

   

   사용할 아이피는 IANA 정보에 따라서 239.0.0.0 와 239.255.255.255 사이의 아이피를 선택합니다.

   MComms TV 에도 정보가 나와 있으니 참조하면 됩니다.


▷ 시스템에서 사용하지 않는 포트를 선택합니다.

   Windows Vista, 7, 2008 는 포트 번호 49152 와 65535, 예전 윈도즈는 1025 와 5000 그리고 Linux

   는 32768 와 61000 번호를 선택합니다.

   

   자세한 정보는 여기에 나와 있습니다. MComms TV 



프로그램 설명


sender 가 특정 아이피로 멀티캐스트그룹을 만들고, 그룹에 참가하는 receiver 에게 루프를 돌면서 메시지를 전송한 것입니다.



실행 후


메시지 전송 후


프로그램 작성 순서


1. 공통 라이브러리


using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;


2. Sender 프로그램


        static void Main(string[] args)
        {
            UdpClient udpclient = new UdpClient();

            IPAddress multicastaddress = IPAddress.Parse("239.0.0.222");
            udpclient.JoinMulticastGroup(multicastaddress);
            IPEndPoint remoteEP = new IPEndPoint(multicastaddress, 2222);

            byte[] buffer = null;

            Console.WriteLine("Press ENTER to start sending message");
            Console.ReadLine();

            for (int i = 0; i <= 8000; i++)
            {
                buffer = Encoding.Unicode.GetBytes(i.ToString());
                udpclient.Send(buffer, buffer.Length, remoteEP);
                Console.WriteLine("Sent : {0}", i.ToString());
            }

            buffer = Encoding.Unicode.GetBytes("quit");
            udpclient.Send(buffer, buffer.Length, remoteEP);

            udpclient.Close();

            Console.WriteLine("All Done! Press ENTER to quit.");
            Console.ReadLine();
        }


3. Receiver 프로그램


        static void Main(string[] args)
        {
            UdpClient client = new UdpClient();

            client.ExclusiveAddressUse = false;
            IPEndPoint localEp = new IPEndPoint(IPAddress.Any, 2222);

            client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
            client.ExclusiveAddressUse = false;

            client.Client.Bind(localEp);

            IPAddress multicastaddress = IPAddress.Parse("239.0.0.222");
            client.JoinMulticastGroup(multicastaddress);

            Console.WriteLine("Listening this will quit");

            while(true)
            {
                byte[] data = client.Receive(ref localEp);
                string strData = Encoding.Unicode.GetString(data);
                Console.WriteLine("received data : {0}", strData);

                if (strData == "quit")
                    break;
            }

            Console.WriteLine("quit the program to ENTER");
            Console.ReadLine();
        }
posted by 따시쿵