UdpClient Classe

Definizione

Fornisce servizi di rete UDP (User Datagram Protocol).

public ref class UdpClient : IDisposable
public class UdpClient : IDisposable
type UdpClient = class
    interface IDisposable
Public Class UdpClient
Implements IDisposable
Ereditarietà
UdpClient
Implementazioni

Esempio

Nell'esempio seguente viene stabilita una UdpClient connessione usando il nome www.contoso.com host sulla porta 11000. Un piccolo messaggio stringa viene inviato a due computer host remoti separati. Il Receive metodo blocca l'esecuzione fino a quando non viene ricevuto un messaggio. Usando l'oggetto IPEndPoint passato a Receive, viene rilevata l'identità dell'host che risponde.

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

Commenti

La UdpClient classe fornisce metodi semplici per l'invio e la ricezione di datagrammi UDP senza connessione in modalità sincrona. Poiché UDP è un protocollo di trasporto senza connessione, non è necessario stabilire una connessione host remota prima di inviare e ricevere dati. È tuttavia possibile stabilire un host remoto predefinito in uno dei due modi seguenti:

  • Creare un'istanza della UdpClient classe usando il nome host remoto e il numero di porta come parametri.

  • Creare un'istanza della UdpClient classe e quindi chiamare il Connect metodo .

È possibile usare uno dei metodi di invio forniti in UdpClient per inviare dati a un dispositivo remoto. Usare il Receive metodo per ricevere dati da host remoti.

Note

Non chiamare Send usando un nome host o IPEndPoint se è già stato specificato un host remoto predefinito. In questo caso, UdpClient genererà un'eccezione.

UdpClient i metodi consentono anche di inviare e ricevere datagrammi multicast. Utilizzare il JoinMulticastGroup metodo per sottoscrivere un UdpClient gruppo multicast. Usare il metodo per annullare la DropMulticastGroup sottoscrizione UdpClient a un gruppo multicast.

Costruttori

Nome Descrizione
UdpClient()

Inizializza una nuova istanza della classe UdpClient.

UdpClient(AddressFamily)

Inizializza una nuova istanza della classe UdpClient.

UdpClient(Int32, AddressFamily)

Inizializza una nuova istanza della UdpClient classe e la associa al numero di porta locale fornito.

UdpClient(Int32)

Inizializza una nuova istanza della UdpClient classe e la associa al numero di porta locale fornito.

UdpClient(IPEndPoint)

Inizializza una nuova istanza della UdpClient classe e la associa all'endpoint locale specificato.

UdpClient(String, Int32)

Inizializza una nuova istanza della UdpClient classe e stabilisce un host remoto predefinito.

Proprietà

Nome Descrizione
Active

Ottiene o imposta un valore che indica se è stato stabilito un host remoto predefinito.

Available

Ottiene la quantità di dati ricevuti dalla rete disponibile per la lettura.

Client

Ottiene o imposta la rete Socketsottostante.

DontFragment

Ottiene o imposta un Boolean valore che specifica se UdpClient consente di frammentare i datagrammi IP (Internet Protocol).

EnableBroadcast

Ottiene o imposta un Boolean valore che specifica se l'oggetto UdpClient può inviare pacchetti di trasmissione.

ExclusiveAddressUse

Ottiene o imposta un Boolean valore che specifica se UdpClient consente a un solo client di utilizzare una porta.

MulticastLoopback

Ottiene o imposta un Boolean valore che specifica se i pacchetti multicast in uscita vengono recapitati all'applicazione di invio.

Ttl

Ottiene o imposta un valore che specifica il valore TTL (Time to Live) dei pacchetti IP (Internet Protocol) inviati da UdpClient.

Metodi

Nome Descrizione
AllowNatTraversal(Boolean)

Abilita o disabilita l'attraversamento NAT (Network Address Translation) in un'istanza UdpClient di .

BeginReceive(AsyncCallback, Object)

Riceve un datagramma da un host remoto in modo asincrono.

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

Invia un datagramma a un host remoto in modo asincrono. La destinazione è stata specificata in precedenza da una chiamata a Connect.

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

Invia un datagramma a una destinazione in modo asincrono. La destinazione viene specificata da un oggetto EndPoint.

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

Invia un datagramma a una destinazione in modo asincrono. La destinazione viene specificata dal nome host e dal numero di porta.

Close()

Chiude la connessione UDP.

Connect(IPAddress, Int32)

Stabilisce un host remoto predefinito usando l'indirizzo IP e il numero di porta specificati.

Connect(IPEndPoint)

Stabilisce un host remoto predefinito usando l'endpoint di rete specificato.

Connect(String, Int32)

Stabilisce un host remoto predefinito usando il nome host e il numero di porta specificati.

Dispose()

Rilascia le risorse gestite e non gestite usate da UdpClient.

Dispose(Boolean)

Rilascia le risorse non gestite usate da UdpClient e, facoltativamente, rilascia le risorse gestite.

DropMulticastGroup(IPAddress, Int32)

Lascia un gruppo multicast.

DropMulticastGroup(IPAddress)

Lascia un gruppo multicast.

EndReceive(IAsyncResult, IPEndPoint)

Termina una ricezione asincrona in sospeso.

EndSend(IAsyncResult)

Termina un invio asincrono in sospeso.

Equals(Object)

Determina se l'oggetto specificato è uguale all'oggetto corrente.

(Ereditato da Object)
GetHashCode()

Funge da funzione hash predefinita.

(Ereditato da Object)
GetType()

Ottiene il Type dell'istanza corrente.

(Ereditato da Object)
JoinMulticastGroup(Int32, IPAddress)

Aggiunge un oggetto UdpClient a un gruppo multicast.

JoinMulticastGroup(IPAddress, Int32)

Aggiunge un UdpClient oggetto a un gruppo multicast con la durata (TTL) specificata.

JoinMulticastGroup(IPAddress, IPAddress)

Aggiunge un oggetto UdpClient a un gruppo multicast.

JoinMulticastGroup(IPAddress)

Aggiunge un oggetto UdpClient a un gruppo multicast.

MemberwiseClone()

Crea una copia superficiale del Objectcorrente.

(Ereditato da Object)
Receive(IPEndPoint)

Restituisce un datagramma UDP inviato da un host remoto.

ReceiveAsync()

Restituisce un datagramma UDP in modo asincrono inviato da un host remoto.

Send(Byte[], Int32, IPEndPoint)

Invia un datagramma UDP all'host nell'endpoint remoto specificato.

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

Invia un datagramma UDP a una porta specificata in un host remoto specificato.

Send(Byte[], Int32)

Invia un datagramma UDP a un host remoto.

SendAsync(Byte[], Int32, IPEndPoint)

Invia un datagramma UDP in modo asincrono a un host remoto.

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

Invia un datagramma UDP in modo asincrono a un host remoto.

SendAsync(Byte[], Int32)

Invia un datagramma UDP in modo asincrono a un host remoto.

ToString()

Restituisce una stringa che rappresenta l'oggetto corrente.

(Ereditato da Object)

Implementazioni dell'interfaccia esplicita

Nome Descrizione
IDisposable.Dispose()

Questa API supporta l'infrastruttura del prodotto e non è previsto che venga usata direttamente dal codice.

Rilascia tutte le risorse usate da UdpClient.

Si applica a

Vedi anche