Ler em inglês

Partilhar via


UdpClient.JoinMulticastGroup Método

Definição

Adiciona um UdpClient para um grupo de multicast.

Sobrecargas

JoinMulticastGroup(IPAddress)

Adiciona um UdpClient para um grupo de multicast.

JoinMulticastGroup(Int32, IPAddress)

Adiciona um UdpClient para um grupo de multicast.

JoinMulticastGroup(IPAddress, Int32)

Adiciona um UdpClient para um grupo de multicast com a TTL (vida útil) especificada.

JoinMulticastGroup(IPAddress, IPAddress)

Adiciona um UdpClient para um grupo de multicast.

JoinMulticastGroup(IPAddress)

Origem:
UDPClient.cs
Origem:
UDPClient.cs
Origem:
UDPClient.cs

Adiciona um UdpClient para um grupo de multicast.

C#
public void JoinMulticastGroup (System.Net.IPAddress multicastAddr);

Parâmetros

multicastAddr
IPAddress

O multicast IPAddress do grupo que você deseja ingressar.

Exceções

O Socket subjacente foi fechado.

Ocorreu um erro ao acessar o soquete.

O endereço IP não é compatível com o valor AddressFamily que define o esquema de endereçamento do soquete.

Exemplos

O exemplo de código a seguir demonstra como ingressar em um grupo multicast fornecendo um endereço multicast.

C#
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.IO;
using System.Threading;

namespace Mssc.TransportProtocols.Utilities
{

  // The following Receive class is used by both the ClientOriginator and
  // the ClientTarget class to receive data from one another..
  public class Receive
  {
    // The following static method performs the actual data
    // exchange. In particular, it performs the following tasks:
    // 1)Establishes a communication endpoint.
    // 2)Receive data through this end point on behalf of the
    // caller.
    // 3) Returns the received data in ASCII format.
    public static string ReceiveUntilStop(UdpClient c)
    {
        String strData = "";
        String Ret = "";
        ASCIIEncoding ASCII = new ASCIIEncoding();

        // Establish the communication endpoint.
        IPEndPoint endpoint = new IPEndPoint(IPAddress.IPv6Any, 50);

        while (!strData.Equals("Over"))
        {
          Byte[] data = c.Receive(ref endpoint);
          strData = ASCII.GetString(data);
          Ret += strData  + "\n";
        }
        return Ret;
    }
  }

  // The following Send class is used by both the ClientOriginator and
  // ClientTarget classes to send data to one another.
  public class Send
  {
    private static char[] greetings = { 'H', 'e', 'l', 'l', 'o', ' ',
                                      'T', 'a', 'r', 'g', 'e', 't', '.' };
    private static char[] nice      = { 'H', 'a', 'v', 'e', ' ', 'a', ' ', 'n', 'i',
                                      'c', 'e', ' ', 'd', 'a', 'y', '.' };
    private static char [] eom      = { 'O', 'v', 'e', 'r'};

    private static char[] tGreetings = { 'H', 'e', 'l', 'l', 'o', ' ',
                                       'O', 'r', 'i', 'g', 'i', 'n', 'a', 't', 'o', 'r', '!' };
    private static char[] tNice  = { 'Y', 'o', 'u', ' ', 't', 'o', 'o', '.'};

    // The following static method sends data to the ClientTarget on
    // behalf of the ClientOriginator.
    public static void OriginatorSendData(UdpClient c, IPEndPoint ep)
    {
      Console.WriteLine(new string(greetings));
      c.Send(GetByteArray(greetings), greetings.Length, ep);
      Thread.Sleep(1000);

      Console.WriteLine(new String(nice));
      c.Send(GetByteArray(nice), nice.Length, ep);

      Thread.Sleep(1000);
      Console.WriteLine(new String(eom));
      c.Send(GetByteArray(eom), eom.Length, ep);
    }

    // The following static method sends data to the ClientOriginator on
    // behalf of the ClientTarget.
    public static void TargetSendData(UdpClient c, IPEndPoint ep)
    {
      Console.WriteLine(new string(tGreetings));
      c.Send(GetByteArray(tGreetings), tGreetings.Length, ep);
      Thread.Sleep(1000);

      Console.WriteLine(new String(tNice));
      c.Send(GetByteArray(tNice), tNice.Length, ep);

      Thread.Sleep(1000);
      Console.WriteLine(new String(eom));
      c.Send(GetByteArray(eom), eom.Length, ep);
    }
    // Internal utility
    private static Byte[] GetByteArray(Char[] ChArray)
    {
      Byte[] Ret = new Byte[ChArray.Length];
      for (int i = 0; i < ChArray.Length; i++)
        Ret[i] = (Byte) ChArray[i];
      return Ret;
    }
  }

  // The ClientTarget class is the receiver of the ClientOriginator
  // messages. The StartMulticastConversation method contains the
  // logic for exchanging data between the ClientTarget and its
  // counterpart ClientOriginator in a multicast operation.
  public class ClientTarget
  {
    private static UdpClient m_ClientTarget;
    private static IPAddress m_GrpAddr;

    // The following StartMulticastConversation method connects the UDP
    // ClientTarget with the ClientOriginator.
    // It performs the following main tasks:
    // 1)Creates a UDP client to receive data on a specific port and using
    // IPv6 addresses. The port is the same one used by the ClientOriginator
    // to define its communication endpoint.
    // 2)Joins or creates a multicast group at the specified address.
    // 3)Defines the endpoint port to send data to the ClientOriginator.
    // 4)Receives data from the ClientOriginator until the end of the
    // communication.
    // 5)Sends data to the ClientOriginator.
    // Note this method is the counterpart of the
    // ClientOriginator.ConnectOriginatorAndTarget().
    public static void StartMulticastConversation()
    {
      string Ret;

      // Bind and listen on port 1000. Specify the IPv6 address family type.
      m_ClientTarget = new UdpClient(1000, AddressFamily.InterNetworkV6);

      // Join or create a multicast group
      m_GrpAddr = IPAddress.Parse("FF01::1");

      // Use the overloaded JoinMulticastGroup method.
      // Refer to the ClientOriginator method to see how to use the other
      // methods.
      m_ClientTarget.JoinMulticastGroup(m_GrpAddr);

      // Define the endpoint data port. Note that this port number
      // must match the ClientOriginator UDP port number which is the
      // port on which the ClientOriginator is receiving data.
      IPEndPoint ClientOriginatordest = new IPEndPoint(m_GrpAddr, 2000);

      // Receive data from the ClientOriginator.
      Ret = Receive.ReceiveUntilStop(m_ClientTarget);
      Console.WriteLine("\nThe ClientTarget received: " + "\n\n" + Ret + "\n");

      // Done receiving, now respond to the ClientOriginator.

      // Wait to make sure the ClientOriginator is ready to receive.
      Thread.Sleep(2000);

      Console.WriteLine("\nThe ClientTarget sent:\n");

      Send.TargetSendData(m_ClientTarget, ClientOriginatordest);

      // Exit the multicast conversation.
      m_ClientTarget.DropMulticastGroup(m_GrpAddr);
    }
  }

  // The following ClientOriginator class starts the multicast conversation
  // with the ClientTarget class..
  // It performs the following main tasks:
  // 1)Creates a socket and binds it to the port on which to communicate.
  // 2)Specifies that the connection must use an IPv6 address.
  // 3)Joins or create a multicast group.
  //   Note that the multicast address ranges to use are specified
  //   in the RFC#2375.
  // 4)Defines the endpoint to send the data to and starts the
  // client target (ClientTarget) thread.
  public class ClientOriginator
  {
    private static UdpClient clientOriginator;
    private static IPAddress m_GrpAddr;
    private static IPEndPoint m_ClientTargetdest;
    private static Thread m_t;

    // The ConnectOriginatorAndTarget method connects the
    // ClientOriginator with the ClientTarget.
    // It performs the following main tasks:
    // 1)Creates a UDP client to receive data on a specific port
    //   using IPv6 addresses.
    // 2)Joins or create a multicast group at the specified address.
    // 3)Defines the endpoint port to send data to on the ClientTarget.
    // 4)Starts the ClientTarget thread that also creates the ClientTarget object.
    // Note this method is the counterpart of the
    // ClientTarget.StartMulticastConversation().
    public static bool ConnectOriginatorAndTarget()
    {
      try
      {

        // Bind and listen on port 2000. This constructor creates a socket
        // and binds it to the port on which to receive data. The family
        // parameter specifies that this connection uses an IPv6 address.
        clientOriginator = new UdpClient(2000, AddressFamily.InterNetworkV6);

        // Join or create a multicast group. The multicast address ranges
        // to use are specified in RFC#2375. You are free to use
        // different addresses.

        // Transform the string address into the internal format.
        m_GrpAddr = IPAddress.Parse("FF01::1");

        // Display the multicast address used.
        Console.WriteLine("Multicast Address: [" + m_GrpAddr.ToString() + "]");

        // Exercise the use of the IPv6MulticastOption.
        Console.WriteLine("Instantiate IPv6MulticastOption(IPAddress)");

        // Instantiate IPv6MulticastOption using one of the
        // overloaded constructors.
        IPv6MulticastOption ipv6MulticastOption = new IPv6MulticastOption(m_GrpAddr);

        // Store the IPAdress multicast options.
        IPAddress group =  ipv6MulticastOption.Group;
        long interfaceIndex = ipv6MulticastOption.InterfaceIndex;

        // Display IPv6MulticastOption properties.
        Console.WriteLine("IPv6MulticastOption.Group: [" + group  + "]");
        Console.WriteLine("IPv6MulticastOption.InterfaceIndex: [" + interfaceIndex + "]");



        // Instantiate IPv6MulticastOption using another
        // overloaded constructor.
        IPv6MulticastOption ipv6MulticastOption2 = new IPv6MulticastOption(group, interfaceIndex);

        // Store the IPAdress multicast options.
        group =  ipv6MulticastOption2.Group;
        interfaceIndex = ipv6MulticastOption2.InterfaceIndex;

        // Display the IPv6MulticastOption2 properties.
        Console.WriteLine("IPv6MulticastOption.Group: [" + group  + "]");
        Console.WriteLine("IPv6MulticastOption.InterfaceIndex: [" + interfaceIndex + "]");

        // Join the specified multicast group using one of the
        // JoinMulticastGroup overloaded methods.
        clientOriginator.JoinMulticastGroup((int)interfaceIndex, group);


        // Define the endpoint data port. Note that this port number
        // must match the ClientTarget UDP port number which is the
        // port on which the ClientTarget is receiving data.
        m_ClientTargetdest = new IPEndPoint(m_GrpAddr, 1000);


        // Start the ClientTarget thread so it is ready to receive.
        m_t = new Thread(new ThreadStart(ClientTarget.StartMulticastConversation));
        m_t.Start();

        // Make sure that the thread has started.
        Thread.Sleep(2000);

        return true;
      }
      catch (Exception e)
      {
        Console.WriteLine("[ClientOriginator.ConnectClients] Exception: " + e.ToString());
        return false;
      }
    }

    // The SendAndReceive performs the data exchange
    // between the ClientOriginator and the ClientTarget classes.
    public static string SendAndReceive()
    {
      string Ret = "";


      // Send data to ClientTarget.
      Console.WriteLine("\nThe ClientOriginator sent:\n");
      Send.OriginatorSendData(clientOriginator, m_ClientTargetdest);

      // Receive data from ClientTarget
      Ret = Receive.ReceiveUntilStop(clientOriginator);

      // Stop the ClientTarget thread
      m_t.Abort();

      // Abandon the multicast group.
      clientOriginator.DropMulticastGroup(m_GrpAddr);


      return Ret;
    }

    //This is the console application entry point.
    public static void Main()
    {
      // Join the multicast group.
      if (ConnectOriginatorAndTarget())
      {
        // Perform a multicast conversation with the ClientTarget.
        string Ret = SendAndReceive();
        Console.WriteLine("\nThe ClientOriginator received: " + "\n\n" + Ret);
      }
      else
      {
        Console.WriteLine("Unable to Join the multicast group");
      }
    }
}
}

Comentários

O JoinMulticastGroup método assina o UdpClient em um grupo multicast usando o especificado IPAddress. Depois de chamar o JoinMulticastGroup método , o subjacente Socket envia um pacote IGMP (Protocolo de Gerenciamento de Grupo da Internet) para o roteador que solicita associação ao grupo multicast. O intervalo de endereços multicast é 224.0.0.0 a 239.255.255.255. Se você especificar um endereço fora desse intervalo ou se o roteador para o qual a solicitação é feita não estiver habilitado para multicast, UdpClient lançará um SocketException. Se você receber um SocketException, use SocketException.ErrorCode para obter o código de erro específico. Depois de obter esse código, você poderá consultar a documentação do código de erro da API do Windows Sockets versão 2 para obter uma descrição detalhada do erro. Depois que o UdpClient for listado com o roteador como um membro do grupo multicast, ele poderá receber datagramas multicast enviados para o especificado IPAddress.

Nota

Você deve criar o usando o UdpClient número da porta multicast; caso contrário, você não poderá receber datagrams multicasted. Não chame o Connect método antes de chamar o JoinMulticastGroup método ou o Receive método não funcionará. Você não precisa pertencer a um grupo multicast para enviar datagramas para um endereço IP multicast.

Antes de ingressar em um grupo multicast, verifique se o soquete está associado à porta ou ao ponto de extremidade. Você faz isso chamando um dos construtores que aceitam uma porta ou um ponto de extremidade como parâmetro.

Para interromper o recebimento de datagramas multicast, chame o DropMulticastGroup método e forneça o IPAddress do grupo do qual você gostaria de retirar.

Nota

No caso IPv6, há vários intervalos de endereços multicast que você pode escolher. Consulte o RFC 2375 do IETF.

Nota

Você não pode chamar JoinMulticastGroup em um UdpClient construído sem uma porta local específica (ou seja, usando o UdpClient() construtor ou UdpClient(AddressFamily) ).

Confira também

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1

JoinMulticastGroup(Int32, IPAddress)

Origem:
UDPClient.cs
Origem:
UDPClient.cs
Origem:
UDPClient.cs

Adiciona um UdpClient para um grupo de multicast.

C#
public void JoinMulticastGroup (int ifindex, System.Net.IPAddress multicastAddr);

Parâmetros

ifindex
Int32

O índice de interface associado ao endereço IP local no qual ingressar o grupo de multicast.

multicastAddr
IPAddress

O multicast IPAddress do grupo que você deseja ingressar.

Exceções

O Socket subjacente foi fechado.

Ocorreu um erro ao acessar o soquete.

Exemplos

C#

// Instantiate IPv6MulticastOption using another
// overloaded constructor.
IPv6MulticastOption ipv6MulticastOption2 = new IPv6MulticastOption(group, interfaceIndex);

// Store the IPAdress multicast options.
group =  ipv6MulticastOption2.Group;
interfaceIndex = ipv6MulticastOption2.InterfaceIndex;

// Display the IPv6MulticastOption2 properties.
Console.WriteLine("IPv6MulticastOption.Group: [" + group  + "]");
Console.WriteLine("IPv6MulticastOption.InterfaceIndex: [" + interfaceIndex + "]");

// Join the specified multicast group using one of the
// JoinMulticastGroup overloaded methods.
clientOriginator.JoinMulticastGroup((int)interfaceIndex, group);

Comentários

Antes de ingressar em um grupo multicast, verifique se o soquete está associado à porta ou ao ponto de extremidade. Você pode fazer isso chamando um dos construtores que aceita uma porta ou um ponto de extremidade como parâmetro.

O infindex parâmetro é usado para identificar uma interface de hardware no mesmo link.

Nota

Há vários intervalos de endereços multicast para escolher. Consulte o RFC 2375 do IETF.

Nota

Você não pode chamar JoinMulticastGroup em um UdpClient construído sem uma porta local específica (ou seja, usando o UdpClient.UdpClient() construtor ou UdpClient.UdpClient(AddressFamily) ).

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1

JoinMulticastGroup(IPAddress, Int32)

Origem:
UDPClient.cs
Origem:
UDPClient.cs
Origem:
UDPClient.cs

Adiciona um UdpClient para um grupo de multicast com a TTL (vida útil) especificada.

C#
public void JoinMulticastGroup (System.Net.IPAddress multicastAddr, int timeToLive);

Parâmetros

multicastAddr
IPAddress

O IPAddress do grupo de multicast no qual ingressar.

timeToLive
Int32

O TTL (vida útil), medido em saltos do roteador.

Exceções

O TTL fornecido não está entre 0 e 255

O Socket subjacente foi fechado.

Ocorreu um erro ao acessar o soquete.

multicastAddr é null.

O endereço IP não é compatível com o valor AddressFamily que define o esquema de endereçamento do soquete.

Exemplos

O exemplo a seguir demonstra como unir um grupo multicast fornecendo dois parâmetros, um endereço multicast e um número que representa o TTL.

C#
UdpClient udpClient = new UdpClient();
// Creates an IPAddress to use to join and drop the multicast group.
IPAddress multicastIpAddress = IPAddress.Parse("239.255.255.255");

try{
     // The packet dies after 50 router hops.
     udpClient.JoinMulticastGroup(multicastIpAddress, 50);
}
catch ( Exception e ){
    Console.WriteLine( e.ToString());
}

Comentários

O JoinMulticastGroup método assina o UdpClient em um grupo multicast usando o especificado IPAddress. Depois de chamar o JoinMulticastGroup método , o subjacente Socket envia um pacote IGMP (Protocolo de Gerenciamento de Grupo da Internet) para o roteador que solicita associação ao grupo multicast. O intervalo de endereços multicast é 224.0.0.0 a 239.255.255.255. Se você especificar um endereço fora desse intervalo ou se o roteador para o qual a solicitação é feita não estiver habilitado para multicast, UdpClient lançará um SocketException. Se você receber um SocketException, use SocketException.ErrorCode para obter o código de erro específico. Depois de obter esse código, você poderá consultar a documentação do código de erro da API do Windows Sockets versão 2 para obter uma descrição detalhada do erro. O timeToLive parâmetro especifica quantos saltos de roteador serão permitidos para um datagrama multicasted antes de serem descartados. Depois que o UdpClient for listado com o roteador como um membro do grupo multicast, ele poderá receber datagramas multicast enviados para o especificado IPAddress.

Nota

Você deve criar o UdpClient usando o número da porta multicast, caso contrário, não poderá receber datagramas multicast. Não chame o Connect método antes de chamar o JoinMulticastGroup método ou o método receive não funcionará. Você não precisa pertencer a um grupo multicast para enviar datagramas para um endereço IP multicast.

Antes de ingressar em um grupo multicast, verifique se o soquete está associado à porta ou ao ponto de extremidade. Você faz isso chamando um dos construtores que aceitam como parâmetro uma porta ou um ponto de extremidade.

Para interromper o recebimento de datagramas multicast, chame o DropMulticastGroup método e forneça o IPAddress do grupo do qual você gostaria de retirar.

Nota

Você não pode chamar JoinMulticastGroup em um UdpClient construído sem uma porta local específica (ou seja, usando o UdpClient() construtor ou UdpClient(AddressFamily) ).

Confira também

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1

JoinMulticastGroup(IPAddress, IPAddress)

Origem:
UDPClient.cs
Origem:
UDPClient.cs
Origem:
UDPClient.cs

Adiciona um UdpClient para um grupo de multicast.

C#
public void JoinMulticastGroup (System.Net.IPAddress multicastAddr, System.Net.IPAddress localAddress);

Parâmetros

multicastAddr
IPAddress

O multicast IPAddress do grupo que você deseja ingressar.

localAddress
IPAddress

O IPAddress local.

Exceções

O Socket subjacente foi fechado.

Ocorreu um erro ao acessar o soquete.

Exemplos

O exemplo de código a seguir mostra o uso do JoinMulticastGroup método .

C#
// Subscribe to a multicast group.
public static void DoJoinMulticastGroup(UdpClient u, string mcast)
{
    IPAddress[] multicastAddress = Dns.GetHostAddresses(mcast);

    u.JoinMulticastGroup(multicastAddress[0]);
    Console.WriteLine("Joined multicast Address {0}",
        multicastAddress[0]);
}

Comentários

Antes de ingressar em um grupo multicast, verifique se o soquete está associado à porta ou ao ponto de extremidade. Você pode fazer isso chamando um dos construtores que aceita uma porta ou um ponto de extremidade como parâmetro.

Nota

Há vários intervalos de endereços multicast para escolher. Você pode encontrá-los no IETF RFC 2375.

Nota

Você não pode chamar JoinMulticastGroup em um UdpClient construído sem uma porta local específica (ou seja, usando o UdpClient() construtor ou UdpClient(AddressFamily) ).

Aplica-se a

.NET 9 e outras versões
Produto Versões
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1