3

it only works when I use the same port(9050 or some other) in both send and receive, then how can I receive the multicast in more than one client at the same time on the same computer? that creates a socket error of using the same port more than once if I use the same port in more than one client

http://codeidol.com/csharp/csharp-network/IP-Multicasting/Csharp-IP-Multicast-Support/

    using System;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    class UdpClientMultiSend
    {
      public static void Main()
      {
       UdpClient sock = new UdpClient();
       IPEndPoint iep = new IPEndPoint(IPAddress.Parse("224.100.0.1"), 9050);
       byte[] data = Encoding.ASCII.GetBytes("This is a test message");
       sock.Send(data, data.Length, iep);
       sock.Close();
      }
    }




using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
class UdpClientMultiRecv
{
  public static void Main()
  {
   UdpClient sock = new UdpClient(9050);
   Console.WriteLine("Ready to receive…");
   sock.JoinMulticastGroup(IPAddress.Parse("224.100.0.1"), 50);
   IPEndPoint iep = new IPEndPoint(IPAddress.Any, 0);
   byte[] data = sock.Receive(ref iep);
   string stringData = Encoding.ASCII.GetString(data, 0, data.Length);
   Console.WriteLine("received: {0} from: {1}", stringData, iep.ToString());
   sock.Close();
  }
}

2 Answers2

3

See the answer to this post: Connecting two UDP clients to one port (Send and Receive)

You have to set the socket option before binding.

static void Main(string[] args)
{
    IPEndPoint localpt = new IPEndPoint(IPAddress.Any, 6000);

    UdpClient udpServer = new UdpClient();
    udpServer.Client.SetSocketOption(
        SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
    udpServer.Client.Bind(localpt);

    UdpClient udpServer2 = new UdpClient();
    udpServer2.Client.SetSocketOption(
        SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

    udpServer2.Client.Bind(localpt); // <<---------- No Exception here

    Console.WriteLine("Finished.");
    Console.ReadLine();
}
Community
  • 1
  • 1
Grant
  • 1,608
  • 16
  • 14
0

Set the ExclusiveAddressUse property to false on the udpClient class.

See the documentation for a full description of how you use it.

Simon Halsey
  • 5,459
  • 1
  • 21
  • 32