Send and receive data on a udp socket.

I am writing a simple code to send and receive data on a udp socket.

 the code works ok except for the data is getting received thrice .

 I am new to this so bare with me... :)
 
Sendrer Code:

 Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
           server.EnableBroadcast = false;
            server.ExclusiveAddressUse = false;
  
        IPEndPoint iep = new IPEndPoint(IPAddress.Parse("224.100.0.1"), 9050);
            byte[] data = Encoding.ASCII.GetBytes(textBox1.Text.Trim());

            server.SendTo(data, iep);
            server.Close();

        }

        private void OnReceive(IAsyncResult ar)
        {

           
try
            {

                UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).u;
                IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).e;

                UdpState s = new UdpState();
                s.e = e;

                s.u = u;
                Byte[] receiveBytes = u.EndReceive(ar, ref e);

                string receiveString = Encoding.ASCII.GetString(receiveBytes);
                s.e = e;

                listBox1.Items.Add("Received:" + receiveString + e.Address.ToString());
                u.BeginReceive(new AsyncCallback(OnReceive), s);

            }
            catch (Exception ex)

            {
                MessageBox.Show(ex.Message);

            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            CheckForIllegalCrossThreadCalls = false;
//Will remove later
        }

        private void StartReceive_Click(object sender, EventArgs eA)
        {

            IPEndPoint iep = new IPEndPoint(IPAddress.Parse("224.100.0.1"), 9050);
            IPEndPoint e = new IPEndPoint(IPAddress.Any, 9050);

            UdpClient u = new UdpClient(e);
         
            u.Client.Blocking = false;
            UdpState s = new UdpState();

            s.e = e;
            s.u = u;

            s.u.Client.DontFragment = true;
            s.u.Client.Ttl = 1;

            listBox1.Items.Add("listening for messages");
            u.JoinMulticastGroup(IPAddress.Parse("224.100.0.1"));

           u.BeginReceive(new AsyncCallback(OnReceive), s);
        }

        public class
UdpState
        {

            public IPEndPoint e;
           public UdpClient u;

        }
 

sfdsf.jpg

Ebook Download
View all
Learn
View all