UdpClient.JoinMulticastGroup UdpClient.JoinMulticastGroup UdpClient.JoinMulticastGroup UdpClient.JoinMulticastGroup Method

定義

UdpClient 加入至多點傳送群組。Adds a UdpClient to a multicast group.

多載

JoinMulticastGroup(IPAddress) JoinMulticastGroup(IPAddress) JoinMulticastGroup(IPAddress) JoinMulticastGroup(IPAddress)

UdpClient 加入至多點傳送群組。Adds a UdpClient to a multicast group.

JoinMulticastGroup(Int32, IPAddress) JoinMulticastGroup(Int32, IPAddress) JoinMulticastGroup(Int32, IPAddress) JoinMulticastGroup(Int32, IPAddress)

UdpClient 加入至多點傳送群組。Adds a UdpClient to a multicast group.

JoinMulticastGroup(IPAddress, Int32) JoinMulticastGroup(IPAddress, Int32) JoinMulticastGroup(IPAddress, Int32) JoinMulticastGroup(IPAddress, Int32)

使用指定的存活時間 (Time to Live,TTL) 將 UdpClient 加入至多點傳送群組。Adds a UdpClient to a multicast group with the specified Time to Live (TTL).

JoinMulticastGroup(IPAddress, IPAddress) JoinMulticastGroup(IPAddress, IPAddress) JoinMulticastGroup(IPAddress, IPAddress) JoinMulticastGroup(IPAddress, IPAddress)

UdpClient 加入至多點傳送群組。Adds a UdpClient to a multicast group.

JoinMulticastGroup(IPAddress) JoinMulticastGroup(IPAddress) JoinMulticastGroup(IPAddress) JoinMulticastGroup(IPAddress)

UdpClient 加入至多點傳送群組。Adds a UdpClient to a multicast group.

public:
 void JoinMulticastGroup(System::Net::IPAddress ^ multicastAddr);
public void JoinMulticastGroup (System.Net.IPAddress multicastAddr);
member this.JoinMulticastGroup : System.Net.IPAddress -> unit
Public Sub JoinMulticastGroup (multicastAddr As IPAddress)

參數

multicastAddr
IPAddress IPAddress IPAddress IPAddress

您要聯結的群組其多點傳送 IPAddressThe multicast IPAddress of the group you want to join.

例外狀況

存取通訊端時發生錯誤。An error occurred when accessing the socket.

IP 位址與 AddressFamily 值不相容,這個值定義著通訊端的定址配置。The IP address is not compatible with the AddressFamily value that defines the addressing scheme of the socket.

範例

下列程式碼範例示範如何藉由提供多播位址來聯結多播群組。The following code example demonstrates how to join a multicast group by providing a multicast address.

#using <System.dll>

using namespace System;
using namespace System::Net;
using namespace System::Net::Sockets;
using namespace System::Text;
using namespace System::IO;
using namespace System::Threading;

// The following Receive class is used by both the ClientOriginator and
// the ClientTarget class to receive data from one another..
public ref class Receive
{
public:

   // 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.
   static String^ ReceiveUntilStop( UdpClient^ c )
   {
      String^ strData = "";
      String^ Ret = "";
      ASCIIEncoding^ ASCII = gcnew ASCIIEncoding;
      
      // Establish the communication endpoint.
      IPEndPoint^ endpoint = gcnew IPEndPoint( IPAddress::IPv6Any,50 );
      while (  !strData->Equals( "Over" ) )
      {
         array<Byte>^data = c->Receive( endpoint );
         strData = ASCII->GetString( data );
         Ret = String::Concat( 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 ref class Send
{
private:
   static array<Char>^greetings = {'H','e','l','l','o',' ','T','a','r','g','e','t','->'};
   static array<Char>^nice = {'H','a','v','e',' ','a',' ','n','i','c','e',' ','d','a','y','->'};
   static array<Char>^eom = {'O','v','e','r'};
   static array<Char>^tGreetings = {'H','e','l','l','o',' ','O','r','i','g','i','n','a','t','o','r','!'};
   static array<Char>^tNice = {'Y','o','u',' ','t','o','o','->'};

public:

   // The following static method sends data to the ClientTarget on
   // behalf of the ClientOriginator.
   static void OriginatorSendData( UdpClient^ c, IPEndPoint^ ep )
   {
      Console::WriteLine( gcnew String( greetings ) );
      c->Send( GetByteArray( greetings ), greetings->Length, ep );
      Thread::Sleep( 1000 );
      Console::WriteLine( gcnew String( nice ) );
      c->Send( GetByteArray( nice ), nice->Length, ep );
      Thread::Sleep( 1000 );
      Console::WriteLine( gcnew String( eom ) );
      c->Send( GetByteArray( eom ), eom->Length, ep );
   }


   // The following static method sends data to the ClientOriginator on
   // behalf of the ClientTarget.
   static void TargetSendData( UdpClient^ c, IPEndPoint^ ep )
   {
      Console::WriteLine( gcnew String( tGreetings ) );
      c->Send( GetByteArray( tGreetings ), tGreetings->Length, ep );
      Thread::Sleep( 1000 );
      Console::WriteLine( gcnew String( tNice ) );
      c->Send( GetByteArray( tNice ), tNice->Length, ep );
      Thread::Sleep( 1000 );
      Console::WriteLine( gcnew String( eom ) );
      c->Send( GetByteArray( eom ), eom->Length, ep );
   }


private:

   // Internal utility
   static array<Byte>^ GetByteArray( array<Char>^ChArray )
   {
      array<Byte>^Ret = gcnew array<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 ref class ClientTarget
{
private:
   static UdpClient^ m_ClientTarget;
   static IPAddress^ m_GrpAddr;

public:

   // 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().
   static void StartMulticastConversation()
   {
      String^ Ret;
      
      // Bind and listen on port 1000. Specify the IPv6 address family type.
      m_ClientTarget = gcnew 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 = gcnew IPEndPoint( m_GrpAddr,2000 );
      
      // Receive data from the ClientOriginator.
      Ret = Receive::ReceiveUntilStop( m_ClientTarget );
      Console::WriteLine( "\nThe ClientTarget received: \n\n {0}\n", Ret );
      
      // 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 ref class ClientOriginator
{
private:
   static UdpClient^ clientOriginator;
   static IPAddress^ m_GrpAddr;
   static IPEndPoint^ m_ClientTargetdest;
   static Thread^ m_t;

public:

   // 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().
   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 = gcnew 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: [ {0}]", m_GrpAddr );
         
         // Exercise the use of the IPv6MulticastOption.
         Console::WriteLine( "Instantiate IPv6MulticastOption(IPAddress)" );
         
         // Instantiate IPv6MulticastOption using one of the
         // overloaded constructors.
         IPv6MulticastOption^ ipv6MulticastOption = gcnew IPv6MulticastOption( m_GrpAddr );
         
         // Store the IPAdress multicast options.
         IPAddress^ group = ipv6MulticastOption->Group;
         __int64 interfaceIndex = ipv6MulticastOption->InterfaceIndex;
         
         // Display IPv6MulticastOption properties.
         Console::WriteLine( "IPv6MulticastOption::Group: [ {0}]", group );
         Console::WriteLine( "IPv6MulticastOption::InterfaceIndex: [ {0}]", interfaceIndex );
         
         // Instantiate IPv6MulticastOption using another
         // overloaded constructor.
         IPv6MulticastOption^ ipv6MulticastOption2 = gcnew IPv6MulticastOption( group,interfaceIndex );
         
         // Store the IPAdress multicast options.
         group = ipv6MulticastOption2->Group;
         interfaceIndex = ipv6MulticastOption2->InterfaceIndex;
         
         // Display the IPv6MulticastOption2 properties.
         Console::WriteLine( "IPv6MulticastOption::Group: [ {0} ]", group );
         Console::WriteLine( "IPv6MulticastOption::InterfaceIndex: [ {0} ]", 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 = gcnew IPEndPoint( m_GrpAddr,1000 );
         
         // Start the ClientTarget thread so it is ready to receive.
         m_t = gcnew Thread( gcnew 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: {0}", e );
         return false;
      }

   }


   // The SendAndReceive performs the data exchange
   // between the ClientOriginator and the ClientTarget classes.
   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.
int main()
{
   
   // Join the multicast group.
   if ( ClientOriginator::ConnectOriginatorAndTarget() )
   {
      
      // Perform a multicast conversation with the ClientTarget.
      String^ Ret = ClientOriginator::SendAndReceive();
      Console::WriteLine( "\nThe ClientOriginator received: \n\n {0}", Ret );
   }
   else
   {
      Console::WriteLine( "Unable to Join the multicast group" );
   }
}


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");
      }
    }
}
}
Imports System
Imports System.Net
Imports System.Net.Sockets
Imports System.Text
Imports System.IO
Imports System.Threading
Imports Microsoft.VisualBasic





' 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 Shared Function ReceiveUntilStop(c As UdpClient) As String
      Dim strData As [String] = ""
      Dim Ret As [String] = ""
      Dim ASCII As New ASCIIEncoding()
      
      ' Establish the communication endpoint.
      Dim endpoint As New IPEndPoint(IPAddress.IPv6Any, 50)
      
      While Not strData.Equals("Over")
         Dim data As [Byte]() = c.Receive(endpoint)
         strData = ASCII.GetString(data)
         Ret += strData + ControlChars.Lf
      End While
      Return Ret
   End Function 'ReceiveUntilStop
End Class 'Receive

' The following Send class is used by both the ClientOriginator and 
' ClientTarget classes to send data to one another.

Public Class Send
   Private Shared greetings As Char() =  {"H"c, "e"c, "l"c, "l"c, "o"c, " "c, "T"c, "a"c, "r"c, "g"c, "e"c, "t"c, "."c}
   Private Shared nice As Char() =  {"H"c, "a"c, "v"c, "e"c, " "c, "a"c, " "c, "n"c, "i"c, "c"c, "e"c, " "c, "d"c, "a"c, "y"c, "."c}
   Private Shared eom As Char() =  {"O"c, "v"c, "e"c, "r"c}
   
   Private Shared tGreetings As Char() =  {"H"c, "e"c, "l"c, "l"c, "o"c, " "c, "O"c, "r"c, "i"c, "g"c, "i"c, "n"c, "a"c, "t"c, "o"c, "r"c, "!"c}
   Private Shared tNice As Char() =  {"Y"c, "o"c, "u"c, " "c, "t"c, "o"c, "o"c, "."c}
   
   
   ' The following static method sends data to the ClientTarget on 
   ' behalf of the ClientOriginator.
   Public Shared Sub OriginatorSendData(c As UdpClient, ep As IPEndPoint)
      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)
   End Sub 'OriginatorSendData
   
   
   ' The following static method sends data to the ClientOriginator on 
   ' behalf of the ClientTarget.
   Public Shared Sub TargetSendData(c As UdpClient, ep As IPEndPoint)
      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)
   End Sub 'TargetSendData
   
   ' Internal utility 
   Public Shared Function GetByteArray(ChArray() As [Char]) As [Byte]()
      Dim Ret(ChArray.Length) As [Byte]
      
      Dim i As Integer
      For i = 0 To ChArray.Length - 1
         Ret(i) = AscW(ChArray(i))
      Next i 
      Return Ret
   End Function 'GetByteArray

End Class 'Send


' 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 Shared m_ClientTarget As UdpClient
   Private Shared m_GrpAddr As IPAddress
   
   
   ' 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 Shared Sub StartMulticastConversation()
      Dim Ret As String
      
      ' 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.
      Dim ClientOriginatordest As New IPEndPoint(m_GrpAddr, 2000)
      
      ' Receive data from the ClientOriginator.
      Ret = Receive.ReceiveUntilStop(m_ClientTarget)
      Console.WriteLine((ControlChars.Lf + "The ClientTarget received: " + ControlChars.Lf + ControlChars.Lf + Ret + ControlChars.Lf))
      
      ' Done receiving, now respond to the ClientOriginator.
      ' Wait to make sure the ClientOriginator is ready to receive.
      Thread.Sleep(2000)
      
      Console.WriteLine(ControlChars.Lf + "The ClientTarget sent:" + ControlChars.Lf)
      
      Send.TargetSendData(m_ClientTarget, ClientOriginatordest)
      
      ' Exit the multicast conversation. 
      m_ClientTarget.DropMulticastGroup(m_GrpAddr)
   End Sub 'StartMulticastConversation
End Class 'ClientTarget


' 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 Shared clientOriginator As UdpClient
   Private Shared m_GrpAddr As IPAddress
   Private Shared m_ClientTargetdest As IPEndPoint
   Private Shared m_t As Thread
   
   
   ' 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 Shared Function ConnectOriginatorAndTarget() As Boolean
      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.
         Dim ipv6MulticastOption As New IPv6MulticastOption(m_GrpAddr)
         
         ' Store the IPAdress multicast options.
         Dim group As IPAddress = ipv6MulticastOption.Group
         Dim interfaceIndex As Long = ipv6MulticastOption.InterfaceIndex
         
         ' Display IPv6MulticastOption properties.
         Console.WriteLine(("IPv6MulticastOption.Group: [" + group.ToString() + "]"))
         Console.WriteLine(("IPv6MulticastOption.InterfaceIndex: [" + interfaceIndex.ToString() + "]"))
         
         ' Instantiate IPv6MulticastOption using another 
         ' overloaded constructor.
         Dim ipv6MulticastOption2 As New IPv6MulticastOption(group, interfaceIndex)
         
         ' Store the IPAdress multicast options.
         group = ipv6MulticastOption2.Group
         interfaceIndex = ipv6MulticastOption2.InterfaceIndex
         
         ' Display the IPv6MulticastOption2 properties.
         Console.WriteLine(("IPv6MulticastOption.Group: [" + group.ToString() + "]"))
         Console.WriteLine(("IPv6MulticastOption.InterfaceIndex: [" + interfaceIndex.ToString() + "]"))
         
         ' Join the specified multicast group using one of the 
         ' JoinMulticastGroup overloaded methods.
         clientOriginator.JoinMulticastGroup(Fix(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(AddressOf ClientTarget.StartMulticastConversation))
         m_t.Start()
         
         ' Make sure that the thread has started.
         Thread.Sleep(2000)
         
         Return True
      Catch e As Exception
         Console.WriteLine(("[ClientOriginator.ConnectClients] Exception: " + e.ToString()))
         Return False
      End Try
   End Function 'ConnectOriginatorAndTarget
   
   
   ' The SendAndReceive performs the data exchange  
   ' between the ClientOriginator and the ClientTarget classes.
   Public Shared Function SendAndReceive() As String
      Dim Ret As String = ""
      
      ' Send data to ClientTarget.
      Console.WriteLine(ControlChars.Lf + "The ClientOriginator sent:" + ControlChars.Lf)
      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
   End Function 'SendAndReceive
   
   
   'This is the console application entry point.
   Public Shared Sub Main()
      ' Join the multicast group.
      If ConnectOriginatorAndTarget() Then
         ' Perform a multicast conversation with the ClientTarget.
         Dim Ret As String = SendAndReceive()
         Console.WriteLine((ControlChars.Lf + "The ClientOriginator received: " + ControlChars.Lf + ControlChars.Lf + Ret))
      Else
         Console.WriteLine("Unable to Join the multicast group")
      End If
   End Sub 'Main
End Class 'ClientOriginator

備註

方法會使用指定UdpClient IPAddress的, 將訂閱到多播群組。 JoinMulticastGroupThe JoinMulticastGroup method subscribes the UdpClient to a multicast group using the specified IPAddress. 呼叫JoinMulticastGroup方法之後, 基礎Socket會將網際網路群組管理通訊協定 (IGMP) 封包傳送至要求多播群組成員資格的路由器。After calling the JoinMulticastGroup method, the underlying Socket sends an Internet Group Management Protocol (IGMP) packet to the router requesting membership to the multicast group. 多播位址範圍是224.0.0.0 到239.255.255.255。The multicast address range is 224.0.0.0 to 239.255.255.255. 如果您指定超出此範圍的位址, 或如果提出要求的路由器未啟用多播, UdpClient將會SocketException擲回。If you specify an address outside this range or if the router to which the request is made is not multicast enabled, UdpClient will throw a SocketException. 如果您收到SocketException, 請使用SocketException.ErrorCode來取得特定的錯誤碼。If you receive a SocketException, use SocketException.ErrorCode to obtain the specific error code. 取得此程式碼之後, 您可以參考Windows socket 第2版 API 錯誤碼檔, 以取得錯誤的詳細描述。Once you have obtained this code, you can refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error. 以路由器作為多播群組的成員列出後, 它就能夠接收傳送至指定IPAddress之的多播資料包。 UdpClientOnce the UdpClient is listed with the router as a member of the multicast group, it will be able to receive multicasted datagrams sent to the specified IPAddress.

注意

您必須使用多播UdpClient埠號碼建立, 否則您將無法接收多播的資料包。You must create the UdpClient using the multicast port number; otherwise, you will not be able to receive multicasted datagrams. 請不要在JoinMulticastGroup呼叫Connect方法之前呼叫方法, 否則Receive方法將無法使用。Do not call the Connect method prior to calling the JoinMulticastGroup method, or the Receive method will not work. 您不需要屬於多播群組, 就能將資料包傳送至多播 IP 位址。You do not need to belong to a multicast group to send datagrams to a multicast IP address.

加入多播群組之前, 請確定通訊端已系結至埠或端點。Before joining a multicast group, make sure the socket is bound to the port or endpoint. 若要這麼做, 您可以呼叫接受埠或端點做為參數的其中一個函式。You do that by calling one of the constructors that accept a port or an endpoint as a parameter.

若要停止接收多播的DropMulticastGroup資料包, 請呼叫方法, 並IPAddress提供您想要從中提取之群組的。To stop receiving multicasted datagrams, call the DropMulticastGroup method and provide the IPAddress of the group from which you would like to withdraw.

注意

在 IPv6 案例中, 您可以選擇數個多播位址範圍。In the IPv6 case, there are several multicast address ranges you can choose from. 請參閱 IETF RFC 2375。Please, refer to the IETF RFC 2375.

注意

您不能JoinMulticastGroup UdpClient在沒有特定本機埠的結構上呼叫 (也就是使用UdpClient()UdpClient(AddressFamily)函式)。You cannot call JoinMulticastGroup on a UdpClient constructed without a specific local port (that is, using the UdpClient() or UdpClient(AddressFamily) constructor).

另請參閱

JoinMulticastGroup(Int32, IPAddress) JoinMulticastGroup(Int32, IPAddress) JoinMulticastGroup(Int32, IPAddress) JoinMulticastGroup(Int32, IPAddress)

UdpClient 加入至多點傳送群組。Adds a UdpClient to a multicast group.

public:
 void JoinMulticastGroup(int ifindex, System::Net::IPAddress ^ multicastAddr);
public void JoinMulticastGroup (int ifindex, System.Net.IPAddress multicastAddr);
member this.JoinMulticastGroup : int * System.Net.IPAddress -> unit
Public Sub JoinMulticastGroup (ifindex As Integer, multicastAddr As IPAddress)

參數

ifindex
Int32 Int32 Int32 Int32

要加入多點傳送群組的本機 IP 位址相關聯的介面索引。The interface index associated with the local IP address on which to join the multicast group.

multicastAddr
IPAddress IPAddress IPAddress IPAddress

您要聯結的群組其多點傳送 IPAddressThe multicast IPAddress of the group you want to join.

例外狀況

存取通訊端時發生錯誤。An error occurred when accessing the socket.

範例

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

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

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

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


// 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);

' Instantiate IPv6MulticastOption using another 
' overloaded constructor.
Dim ipv6MulticastOption2 As New IPv6MulticastOption(group, interfaceIndex)

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

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

' Join the specified multicast group using one of the 
' JoinMulticastGroup overloaded methods.
clientOriginator.JoinMulticastGroup(Fix(interfaceIndex), group)

備註

加入多播群組之前, 請確定通訊端已系結至埠或端點。Before joining a multicast group, be sure the socket is bound to the port or endpoint. 若要這麼做, 您可以呼叫接受通訊埠或端點做為參數的其中一個函式。You can do this by calling one of the constructors that accepts a port or an endpoint as parameter.

infindex參數是用來識別相同連結上的硬體介面。The infindex parameter is used to identify a hardware interface on the same link.

注意

有數個多播位址範圍可供選擇。There are several multicast address ranges to choose from. 請參閱 IETF RFC 2375。Refer to the IETF RFC 2375.

注意

您不能JoinMulticastGroup UdpClient在沒有特定本機埠的結構上呼叫 (也就是使用UdpClient.UdpClient()UdpClient.UdpClient(AddressFamily)函式)。You cannot call JoinMulticastGroup on a UdpClient constructed without a specific local port (that is, using the UdpClient.UdpClient() or UdpClient.UdpClient(AddressFamily) constructor).

JoinMulticastGroup(IPAddress, Int32) JoinMulticastGroup(IPAddress, Int32) JoinMulticastGroup(IPAddress, Int32) JoinMulticastGroup(IPAddress, Int32)

使用指定的存活時間 (Time to Live,TTL) 將 UdpClient 加入至多點傳送群組。Adds a UdpClient to a multicast group with the specified Time to Live (TTL).

public:
 void JoinMulticastGroup(System::Net::IPAddress ^ multicastAddr, int timeToLive);
public void JoinMulticastGroup (System.Net.IPAddress multicastAddr, int timeToLive);
member this.JoinMulticastGroup : System.Net.IPAddress * int -> unit
Public Sub JoinMulticastGroup (multicastAddr As IPAddress, timeToLive As Integer)

參數

multicastAddr
IPAddress IPAddress IPAddress IPAddress

要聯結的多點傳送群組其 IPAddressThe IPAddress of the multicast group to join.

timeToLive
Int32 Int32 Int32 Int32

存活時間 (TTL),以路由器躍點為測量單位。The Time to Live (TTL), measured in router hops.

例外狀況

提供的 TTL 沒有位於 0 和 255 之間The TTL provided is not between 0 and 255

存取通訊端時發生錯誤。An error occurred when accessing the socket.

IP 位址與 AddressFamily 值不相容,這個值定義著通訊端的定址配置。The IP address is not compatible with the AddressFamily value that defines the addressing scheme of the socket.

範例

下列範例示範如何藉由提供兩個參數、多播位址和代表 TTL 的數位來聯結多播群組。The following example demonstrates how to join a multicast group by providing two parameters, a multicast address, and a number that represents the TTL.

UdpClient^ udpClient = gcnew 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() );
}
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());
}
Dim udpClient As New UdpClient()
' Creates an IP address to use to join and drop the multicast group.
Dim multicastIpAddress As IPAddress = IPAddress.Parse("239.255.255.255")

Try
   ' The packet dies after 50 router hops.
   udpClient.JoinMulticastGroup(multicastIpAddress, 50)
Catch e As Exception
   Console.WriteLine(e.ToString())
End Try

備註

方法會使用指定UdpClient IPAddress的, 將訂閱到多播群組。 JoinMulticastGroupThe JoinMulticastGroup method subscribes the UdpClient to a multicast group using the specified IPAddress. 呼叫JoinMulticastGroup方法之後, 基礎Socket會將網際網路群組管理通訊協定 (IGMP) 封包傳送至要求多播群組成員資格的路由器。After calling the JoinMulticastGroup method, the underlying Socket sends an Internet Group Management Protocol (IGMP) packet to the router requesting membership to the multicast group. 多播位址範圍是224.0.0.0 到239.255.255.255。The multicast address range is 224.0.0.0 to 239.255.255.255. 如果您指定超出此範圍的位址, 或如果提出要求的路由器未啟用多播, UdpClient將會SocketException擲回。If you specify an address outside this range or if the router to which the request is made is not multicast enabled, UdpClient will throw a SocketException. 如果您收到SocketException, 請使用SocketException.ErrorCode來取得特定的錯誤碼。If you receive a SocketException, use SocketException.ErrorCode to obtain the specific error code. 取得此程式碼之後, 您可以參考Windows socket 第2版 API 錯誤碼檔, 以取得錯誤的詳細描述。Once you have obtained this code, you can refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error. timeToLive參數會指定多播的資料包在捨棄之前允許的路由器躍點數目。The timeToLive parameter specifies how many router hops will be allowed for a multicasted datagram before being discarded. 以路由器作為多播群組的成員列出後, 它就能夠接收傳送至指定IPAddress之的多播資料包。 UdpClientOnce the UdpClient is listed with the router as a member of the multicast group, it will be able to receive multicasted datagrams sent to the specified IPAddress.

注意

您必須使用多播UdpClient埠號碼建立, 否則將無法接收多播的資料包。You must create the UdpClient using the multicast port number otherwise you will not be able to receive multicasted datagrams. 請不要在JoinMulticastGroup呼叫Connect方法之前呼叫方法, 否則 receive 方法將無法使用。Do not call the Connect method prior to calling the JoinMulticastGroup method or the receive method will not work. 您不需要屬於多播群組, 就能將資料包傳送至多播 IP 位址。You do not need to belong to a multicast group to send datagrams to a multicast IP address.

加入多播群組之前, 請確定通訊端已系結至埠或端點。Before joining a multicast group make sure the socket is bound to the port or endpoint. 若要這麼做, 您可以呼叫接受做為參數的其中一個「埠」或「端點」。You do that by calling one of the constructors that accept as parameter a port or an endpoint.

若要停止接收多播的DropMulticastGroup資料包, 請呼叫方法, 並IPAddress提供您想要從中提取之群組的。To stop receiving multicasted datagrams, call the DropMulticastGroup method and provide the IPAddress of the group from which you would like to withdraw.

注意

您不能JoinMulticastGroup UdpClient在沒有特定本機埠的結構上呼叫 (也就是使用UdpClient()UdpClient(AddressFamily)函式)。You cannot call JoinMulticastGroup on a UdpClient constructed without a specific local port (that is, using the UdpClient() or UdpClient(AddressFamily) constructor).

另請參閱

JoinMulticastGroup(IPAddress, IPAddress) JoinMulticastGroup(IPAddress, IPAddress) JoinMulticastGroup(IPAddress, IPAddress) JoinMulticastGroup(IPAddress, IPAddress)

UdpClient 加入至多點傳送群組。Adds a UdpClient to a multicast group.

public:
 void JoinMulticastGroup(System::Net::IPAddress ^ multicastAddr, System::Net::IPAddress ^ localAddress);
public void JoinMulticastGroup (System.Net.IPAddress multicastAddr, System.Net.IPAddress localAddress);
member this.JoinMulticastGroup : System.Net.IPAddress * System.Net.IPAddress -> unit
Public Sub JoinMulticastGroup (multicastAddr As IPAddress, localAddress As IPAddress)

參數

multicastAddr
IPAddress IPAddress IPAddress IPAddress

您要聯結的群組其多點傳送 IPAddressThe multicast IPAddress of the group you want to join.

localAddress
IPAddress IPAddress IPAddress IPAddress

本機 IPAddressThe local IPAddress.

例外狀況

存取通訊端時發生錯誤。An error occurred when accessing the socket.

範例

下列程式碼範例示範如何使用JoinMulticastGroup方法。The following code example shows the use of the JoinMulticastGroup method.

// Subscribe to a multicast group.
static void DoJoinMulticastGroup( UdpClient^ u, String^ mcast, String^ local )
{
   array<IPAddress^>^ multicastAddress = Dns::GetHostAddresses( mcast );

   u->JoinMulticastGroup( multicastAddress[0] );
   Console::WriteLine(  "Joined multicast Address {0}", multicastAddress );
}
// 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]);
}

備註

在您加入多播群組之前, 請確定通訊端已系結至埠或端點。Before you join a multicast group, be sure that the socket is bound to the port or endpoint. 若要這麼做, 您可以呼叫接受通訊埠或端點做為參數的其中一個函式。You can do this by calling one of the constructors that accepts a port or an endpoint as parameter.

注意

有數個多播位址範圍可供選擇。There are several multicast address ranges to choose from. 您可以在 IETF RFC 2375 中找到它們。You can find them in the IETF RFC 2375.

注意

您不能JoinMulticastGroup UdpClient在沒有特定本機埠的結構上呼叫 (也就是使用UdpClient()UdpClient(AddressFamily)函式)。You cannot call JoinMulticastGroup on a UdpClient constructed without a specific local port (that is, using the UdpClient() or UdpClient(AddressFamily) constructor).

適用於