UdpClient Classe

Définition

Fournit les services de réseau UDP (User Datagram Protocol).

public ref class UdpClient : IDisposable
public class UdpClient : IDisposable
type UdpClient = class
    interface IDisposable
Public Class UdpClient
Implements IDisposable
Héritage
UdpClient
Implémente

Exemples

L’exemple suivant établit une UdpClient connexion à l’aide du nom www.contoso.com d’hôte sur le port 11000. Un petit message de chaîne est envoyé à deux ordinateurs hôtes distants distincts. La méthode bloque l’exécution Receive jusqu’à ce qu’un message soit reçu. À l’aide du IPEndPoint passage à Receive, l’identité de l’hôte de réponse est révélée.

// With this constructor the local port number is arbitrarily assigned.
UdpClient^ udpClient = gcnew UdpClient;
try
{
   udpClient->Connect( "host.contoso.com", 11000 );

   // Send message to the host to which you have connected.
   array<Byte>^sendBytes = Encoding::ASCII->GetBytes( "Is anybody there?" );
   udpClient->Send( sendBytes, sendBytes->Length );

   // Send message to a different host using optional hostname and port parameters.
   UdpClient^ udpClientB = gcnew UdpClient;
   udpClientB->Send( sendBytes, sendBytes->Length, "AlternateHostMachineName", 11000 );

   //IPEndPoint object will allow us to read datagrams sent from any source.
   IPEndPoint^ RemoteIpEndPoint = gcnew IPEndPoint( IPAddress::Any,0 );

   // Block until a message returns on this socket from a remote host.
   array<Byte>^receiveBytes = udpClient->Receive( RemoteIpEndPoint );
   String^ returnData = Encoding::ASCII->GetString( receiveBytes );

   // Use the IPEndPoint object to determine which of these two hosts responded.
   Console::WriteLine( String::Concat( "This is the message you received ", returnData->ToString() ) );
   Console::WriteLine( String::Concat( "This message was sent from ", RemoteIpEndPoint->Address->ToString(), " on their port number ", RemoteIpEndPoint->Port.ToString() ) );
   udpClient->Close();
   udpClientB->Close();
}
catch ( Exception^ e ) 
{
   Console::WriteLine( e->ToString() );
}
// This constructor arbitrarily assigns the local port number.
UdpClient udpClient = new UdpClient(11000);
    try{
         udpClient.Connect("www.contoso.com", 11000);

         // Sends a message to the host to which you have connected.
         Byte[] sendBytes = Encoding.ASCII.GetBytes("Is anybody there?");

         udpClient.Send(sendBytes, sendBytes.Length);

         // Sends a message to a different host using optional hostname and port parameters.
         UdpClient udpClientB = new UdpClient();
         udpClientB.Send(sendBytes, sendBytes.Length, "AlternateHostMachineName", 11000);

         //IPEndPoint object will allow us to read datagrams sent from any source.
         IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

         // Blocks until a message returns on this socket from a remote host.
         Byte[] receiveBytes = udpClient.Receive(ref RemoteIpEndPoint);
         string returnData = Encoding.ASCII.GetString(receiveBytes);

         // Uses the IPEndPoint object to determine which of these two hosts responded.
         Console.WriteLine("This is the message you received " +
                                      returnData.ToString());
         Console.WriteLine("This message was sent from " +
                                     RemoteIpEndPoint.Address.ToString() +
                                     " on their port number " +
                                     RemoteIpEndPoint.Port.ToString());

          udpClient.Close();
          udpClientB.Close();
          }
       catch (Exception e ) {
                  Console.WriteLine(e.ToString());
        }
     ' This constructor arbitrarily assigns the local port number.
     Dim udpClient As New UdpClient(11000)
     Try
        udpClient.Connect("www.contoso.com", 11000)
        
        ' Sends a message to the host to which you have connected.
        Dim sendBytes As [Byte]() = Encoding.ASCII.GetBytes("Is anybody there?")
        
        udpClient.Send(sendBytes, sendBytes.Length)
        
        ' Sends message to a different host using optional hostname and port parameters.
        Dim udpClientB As New UdpClient()
        udpClientB.Send(sendBytes, sendBytes.Length, "AlternateHostMachineName", 11000)
        
        ' IPEndPoint object will allow us to read datagrams sent from any source.
        Dim RemoteIpEndPoint As New IPEndPoint(IPAddress.Any, 0)
        
        ' UdpClient.Receive blocks until a message is received from a remote host.
        Dim receiveBytes As [Byte]() = udpClient.Receive(RemoteIpEndPoint)
        Dim returnData As String = Encoding.ASCII.GetString(receiveBytes)
        
        ' Which one of these two hosts responded?
        Console.WriteLine(("This is the message you received " + _
                                      returnData.ToString()))
         Console.WriteLine(("This message was sent from " + _
                                      RemoteIpEndPoint.Address.ToString() + _ 
                                      " on their port number " + _
                                      RemoteIpEndPoint.Port.ToString()))
        udpClient.Close()
        udpClientB.Close()

     Catch e As Exception
        Console.WriteLine(e.ToString())
     End Try
  End Sub

Remarques

La UdpClient classe fournit des méthodes simples pour l’envoi et la réception de datagrammes UDP sans connexion en mode synchrone bloquant. Étant donné que UDP est un protocole de transport sans connexion, vous n’avez pas besoin d’établir une connexion hôte distante avant d’envoyer et de recevoir des données. Toutefois, vous avez la possibilité d’établir un hôte distant par défaut de l’une des deux façons suivantes :

  • Créez une instance de la classe à l’aide UdpClient du nom d’hôte distant et du numéro de port en tant que paramètres.

  • Créez une instance de la UdpClient classe, puis appelez la Connect méthode.

Vous pouvez utiliser l’une des méthodes d’envoi fournies dans le UdpClient cas où envoyer des données à un appareil distant. Utilisez la Receive méthode pour recevoir des données à partir d’hôtes distants.

Notes

N’appelez Send pas à l’aide d’un nom d’hôte ou IPEndPoint si vous avez déjà spécifié un hôte distant par défaut. Si vous le faites, UdpClient lève une exception.

UdpClient les méthodes vous permettent également d’envoyer et de recevoir des datagrammes de multidiffusion. Utilisez la JoinMulticastGroup méthode pour vous abonner UdpClient à un groupe multidiffusion. Utilisez la DropMulticastGroup méthode pour désinscrire un UdpClient groupe de multidiffusion.

Constructeurs

UdpClient()

Initialise une nouvelle instance de la classe UdpClient.

UdpClient(AddressFamily)

Initialise une nouvelle instance de la classe UdpClient.

UdpClient(Int32)

Initialise une nouvelle instance de la classe UdpClient et la lie au numéro de port local fourni.

UdpClient(Int32, AddressFamily)

Initialise une nouvelle instance de la classe UdpClient et la lie au numéro de port local fourni.

UdpClient(IPEndPoint)

Initialise une nouvelle instance de la classe UdpClient et la lie au point de terminaison local spécifié.

UdpClient(String, Int32)

Initialise une nouvelle instance de la classe UdpClient et établit un hôte distant par défaut.

Propriétés

Active

Obtient ou définit une valeur indiquant si un hôte distant par défaut a été établi.

Available

Obtient le volume de données reçues du réseau et accessibles en lecture.

Client

Obtient ou définit le Socket de réseau sous-jacent.

DontFragment

Obtient ou définit une valeur Boolean qui spécifie si UdpClient autorise la fragmentation des datagrammes IP (Internet Protocol).

EnableBroadcast

Obtient ou définit une Boolean valeur qui spécifie si les UdpClient paquets de diffusion peuvent envoyer des paquets de diffusion.

ExclusiveAddressUse

Obtient ou définit une valeur Boolean qui spécifie si l'élément UdpClient n'autorise qu'un seul client à utiliser un port.

MulticastLoopback

Obtient ou définit une valeur Boolean spécifiant si les paquets multicast sortants sont remis à l'application émettrice.

Ttl

Obtient ou définit une valeur qui spécifie la durée de vie des paquets IP (Internet Protocol) envoyés par UdpClient.

Méthodes

AllowNatTraversal(Boolean)

Active ou désactive la traversée du traducteur d'accès réseau (NAT) sur une instance de UdpClient.

BeginReceive(AsyncCallback, Object)

Reçoit un datagramme d'un hôte distant de manière asynchrone.

BeginSend(Byte[], Int32, AsyncCallback, Object)

Envoie un datagramme à un hôte distant de manière asynchrone. La destination a été spécifiée précédemment par un appel à Connect.

BeginSend(Byte[], Int32, IPEndPoint, AsyncCallback, Object)

Envoie un datagramme à une destination de manière asynchrone. La destination est spécifiée par un EndPoint.

BeginSend(Byte[], Int32, String, Int32, AsyncCallback, Object)

Envoie un datagramme à une destination de manière asynchrone. La destination est spécifiée par le nom d'hôte et le numéro de port.

Close()

Ferme la connexion UDP.

Connect(IPAddress, Int32)

Établit un hôte distant par défaut en utilisant l'adresse IP et le numéro de port spécifiés.

Connect(IPEndPoint)

Établit un hôte distant par défaut en utilisant le point de terminaison du réseau spécifié.

Connect(String, Int32)

Établit un hôte distant par défaut en utilisant le nom d'hôte et le numéro de port spécifiés.

Dispose()

Libère toutes les ressources managées et non managées utilisées par UdpClient.

Dispose(Boolean)

Libère les ressources non managées utilisées par UdpClient et libère éventuellement les ressources managées.

DropMulticastGroup(IPAddress)

Quitte un groupe multicast.

DropMulticastGroup(IPAddress, Int32)

Quitte un groupe multicast.

EndReceive(IAsyncResult, IPEndPoint)

Met fin à une réception asynchrone en attente.

EndSend(IAsyncResult)

Met fin à un envoi asynchrone en attente.

Equals(Object)

Détermine si l'objet spécifié est égal à l'objet actuel.

(Hérité de Object)
Finalize()
GetHashCode()

Fait office de fonction de hachage par défaut.

(Hérité de Object)
GetType()

Obtient le Type de l'instance actuelle.

(Hérité de Object)
JoinMulticastGroup(Int32, IPAddress)

Ajoute UdpClient à un groupe multicast.

JoinMulticastGroup(IPAddress)

Ajoute UdpClient à un groupe multicast.

JoinMulticastGroup(IPAddress, Int32)

Ajoute UdpClient à un groupe multicast avec la durée de vie (TTL, Time to Live) spécifiée.

JoinMulticastGroup(IPAddress, IPAddress)

Ajoute UdpClient à un groupe multicast.

MemberwiseClone()

Crée une copie superficielle du Object actuel.

(Hérité de Object)
Receive(IPEndPoint)

Retourne un datagramme UDP qui a été envoyé par un hôte distant.

ReceiveAsync()

Retourne un datagramme UDP (de manière asynchrone), envoyé par un hôte distant.

ReceiveAsync(CancellationToken)

Retourne un datagramme UDP (de manière asynchrone), envoyé par un hôte distant.

Send(Byte[], Int32)

Envoie un datagramme UDP à un hôte distant.

Send(Byte[], Int32, IPEndPoint)

Envoie un datagramme UDP à l’hôte au point de terminaison distant spécifié.

Send(Byte[], Int32, String, Int32)

Envoie un datagramme UDP à un port indiqué sur un hôte distant spécifié.

Send(ReadOnlySpan<Byte>)

Envoie un datagramme UDP à un hôte distant.

Send(ReadOnlySpan<Byte>, IPEndPoint)

Envoie un datagramme UDP à l’hôte au point de terminaison distant spécifié.

Send(ReadOnlySpan<Byte>, String, Int32)

Envoie un datagramme UDP à un port indiqué sur un hôte distant spécifié.

SendAsync(Byte[], Int32)

Envoie un datagramme UDP à un hôte distant de manière asynchrone.

SendAsync(Byte[], Int32, IPEndPoint)

Envoie un datagramme UDP à un hôte distant de manière asynchrone.

SendAsync(Byte[], Int32, String, Int32)

Envoie un datagramme UDP à un hôte distant de manière asynchrone.

SendAsync(ReadOnlyMemory<Byte>, CancellationToken)

Envoie un datagramme UDP à un hôte distant de manière asynchrone.

SendAsync(ReadOnlyMemory<Byte>, IPEndPoint, CancellationToken)

Envoie un datagramme UDP à un hôte distant de manière asynchrone.

SendAsync(ReadOnlyMemory<Byte>, String, Int32, CancellationToken)

Envoie un datagramme UDP à un hôte distant de manière asynchrone.

ToString()

Retourne une chaîne qui représente l'objet actuel.

(Hérité de Object)

Implémentations d’interfaces explicites

IDisposable.Dispose()

Cette API prend en charge l'infrastructure du produit et n'est pas destinée à être utilisée directement à partir de votre code.

Libère toutes les ressources utilisées par UdpClient.

S’applique à

Voir aussi