UdpClient UdpClient UdpClient UdpClient Class

Definición

Proporciona servicios de red de Protocolo de datagramas de usuarios (UDP).Provides User Datagram Protocol (UDP) network services.

public ref class UdpClient : IDisposable
public class UdpClient : IDisposable
type UdpClient = class
    interface IDisposable
Public Class UdpClient
Implements IDisposable
Herencia
UdpClientUdpClientUdpClientUdpClient
Implementaciones

Ejemplos

En el siguiente ejemplo se UdpClient establece una conexión con el www.contoso.com nombre de host en el puerto 11000.The following example establishes a UdpClient connection using the host name www.contoso.com on port 11000. Se envía un mensaje de cadena pequeño a dos equipos host remotos independientes.A small string message is sent to two separate remote host machines. El Receive método bloquea la ejecución hasta que se recibe un mensaje.The Receive method blocks execution until a message is received. Con el IPEndPoint que se Receivepasa a, se revela la identidad del host que responde.Using the IPEndPoint passed to Receive, the identity of the responding host is revealed.

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

Comentarios

La UdpClient clase proporciona métodos sencillos para enviar y recibir datagramas UDP sin conexión en modo de bloqueo sincrónico.The UdpClient class provides simple methods for sending and receiving connectionless UDP datagrams in blocking synchronous mode. Dado que UDP es un protocolo de transporte sin conexión, no es necesario establecer una conexión de host remoto antes de enviar y recibir datos.Because UDP is a connectionless transport protocol, you do not need to establish a remote host connection prior to sending and receiving data. Sin embargo, tiene la opción de establecer un host remoto predeterminado de una de las dos maneras siguientes:You do, however, have the option of establishing a default remote host in one of the following two ways:

  • Cree una instancia de la UdpClient clase con el nombre de host remoto y el número de puerto como parámetros.Create an instance of the UdpClient class using the remote host name and port number as parameters.

  • Cree una instancia de la UdpClient clase y, a continuación Connect , llame al método.Create an instance of the UdpClient class and then call the Connect method.

Puede usar cualquiera de los métodos de envío proporcionados en UdpClient para enviar datos a un dispositivo remoto.You can use any of the send methods provided in the UdpClient to send data to a remote device. Use el Receive método para recibir datos de hosts remotos.Use the Receive method to receive data from remote hosts.

Nota

No llame Send a mediante un nombre de host IPEndPoint o si ya ha especificado un host remoto predeterminado.Do not call Send using a host name or IPEndPoint if you have already specified a default remote host. Si lo hace, UdpClient producirá una excepción.If you do, UdpClient will throw an exception.

UdpClientlos métodos también permiten enviar y recibir datagramas de multidifusión.UdpClient methods also allow you to send and receive multicast datagrams. Utilice el JoinMulticastGroup método para suscribir UdpClient un a un grupo de multidifusión.Use the JoinMulticastGroup method to subscribe a UdpClient to a multicast group. Use el DropMulticastGroup método para cancelar la suscripción UdpClient de un grupo de multidifusión.Use the DropMulticastGroup method to unsubscribe a UdpClient from a multicast group.

Constructores

UdpClient() UdpClient() UdpClient() UdpClient()

Inicializa una nueva instancia de la clase UdpClient.Initializes a new instance of the UdpClient class.

UdpClient(AddressFamily) UdpClient(AddressFamily) UdpClient(AddressFamily) UdpClient(AddressFamily)

Inicializa una nueva instancia de la clase UdpClient.Initializes a new instance of the UdpClient class.

UdpClient(Int32) UdpClient(Int32) UdpClient(Int32) UdpClient(Int32)

Inicializa una nueva instancia de la clase UdpClient y la enlaza con el número de puerto local especificado.Initializes a new instance of the UdpClient class and binds it to the local port number provided.

UdpClient(Int32, AddressFamily) UdpClient(Int32, AddressFamily) UdpClient(Int32, AddressFamily) UdpClient(Int32, AddressFamily)

Inicializa una nueva instancia de la clase UdpClient y la enlaza con el número de puerto local especificado.Initializes a new instance of the UdpClient class and binds it to the local port number provided.

UdpClient(IPEndPoint) UdpClient(IPEndPoint) UdpClient(IPEndPoint) UdpClient(IPEndPoint)

Inicializa una nueva instancia de la clase UdpClient y la enlaza con el extremo local especificado.Initializes a new instance of the UdpClient class and binds it to the specified local endpoint.

UdpClient(String, Int32) UdpClient(String, Int32) UdpClient(String, Int32) UdpClient(String, Int32)

Inicializa una nueva instancia de la clase UdpClient y establece un host remoto predeterminado.Initializes a new instance of the UdpClient class and establishes a default remote host.

Propiedades

Active Active Active Active

Obtiene o establece un valor que indica si se ha establecido un host remoto predeterminado.Gets or sets a value indicating whether a default remote host has been established.

Available Available Available Available

Obtiene la cantidad de datos recibidos de la red que se pueden leer.Gets the amount of data received from the network that is available to read.

Client Client Client Client

Obtiene o establece el Socket de red subyacente.Gets or sets the underlying network Socket.

DontFragment DontFragment DontFragment DontFragment

Obtiene o establece un valor de Boolean que especifica si UdpClient permite fragmentar los datagramas de protocolo Internet (IP).Gets or sets a Boolean value that specifies whether the UdpClient allows Internet Protocol (IP) datagrams to be fragmented.

EnableBroadcast EnableBroadcast EnableBroadcast EnableBroadcast

Obtiene o establece un valor de Boolean que especifica si UdpClient puede enviar o recibir paquetes de difusión.Gets or sets a Boolean value that specifies whether the UdpClient may send or receive broadcast packets.

ExclusiveAddressUse ExclusiveAddressUse ExclusiveAddressUse ExclusiveAddressUse

Obtiene o establece un valor Boolean que especifica si el objeto UdpClient permite a un único cliente utilizar un puerto.Gets or sets a Boolean value that specifies whether the UdpClient allows only one client to use a port.

MulticastLoopback MulticastLoopback MulticastLoopback MulticastLoopback

Obtiene o establece un valor Boolean que especifica si se entregan paquetes de multidifusión saliente a la aplicación emisora.Gets or sets a Boolean value that specifies whether outgoing multicast packets are delivered to the sending application.

Ttl Ttl Ttl Ttl

Obtiene o establece un valor que especifica el valor de período de vida (TTL) de los paquetes de protocolo de Internet (IP) enviados por UdpClient.Gets or sets a value that specifies the Time to Live (TTL) value of Internet Protocol (IP) packets sent by the UdpClient.

Métodos

AllowNatTraversal(Boolean) AllowNatTraversal(Boolean) AllowNatTraversal(Boolean) AllowNatTraversal(Boolean)

Habilita o deshabilita NAT (Traducción de direcciones de red) transversal en una instancia de UdpClient.Enables or disables Network Address Translation (NAT) traversal on a UdpClient instance.

BeginReceive(AsyncCallback, Object) BeginReceive(AsyncCallback, Object) BeginReceive(AsyncCallback, Object) BeginReceive(AsyncCallback, Object)

Recibe un datagrama de un host remoto de forma asincrónica.Receives a datagram from a remote host asynchronously.

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

Envía un datagrama a un host remoto de forma asincrónica.Sends a datagram to a remote host asynchronously. El destino se especificó anteriormente mediante una llamada a Connect.The destination was specified previously by a call to Connect.

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

Envía un datagrama a un destino de forma asincrónica.Sends a datagram to a destination asynchronously. EndPoint especifica el destino.The destination is specified by a EndPoint.

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

Envía un datagrama a un destino de forma asincrónica.Sends a datagram to a destination asynchronously. El nombre de host y el número de puerto especifican el destino.The destination is specified by the host name and port number.

Close() Close() Close() Close()

Cierra la conexión UDP.Closes the UDP connection.

Connect(IPAddress, Int32) Connect(IPAddress, Int32) Connect(IPAddress, Int32) Connect(IPAddress, Int32)

Establece un host remoto predeterminado mediante la dirección IP y el número de puerto especificados.Establishes a default remote host using the specified IP address and port number.

Connect(IPEndPoint) Connect(IPEndPoint) Connect(IPEndPoint) Connect(IPEndPoint)

Establece un host remoto predeterminado mediante el extremo de red especificado.Establishes a default remote host using the specified network endpoint.

Connect(String, Int32) Connect(String, Int32) Connect(String, Int32) Connect(String, Int32)

Establece un host remoto predeterminado mediante el nombre de host y el número de puerto especificados.Establishes a default remote host using the specified host name and port number.

Dispose() Dispose() Dispose() Dispose()

Libera los recursos administrados y no administrados que utiliza el objeto UdpClient.Releases the managed and unmanaged resources used by the UdpClient.

Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

Libera los recursos no administrados que usa UdpClient y, de forma opcional, libera los recursos administrados.Releases the unmanaged resources used by the UdpClient and optionally releases the managed resources.

DropMulticastGroup(IPAddress) DropMulticastGroup(IPAddress) DropMulticastGroup(IPAddress) DropMulticastGroup(IPAddress)

Abandona un grupo de multidifusión.Leaves a multicast group.

DropMulticastGroup(IPAddress, Int32) DropMulticastGroup(IPAddress, Int32) DropMulticastGroup(IPAddress, Int32) DropMulticastGroup(IPAddress, Int32)

Abandona un grupo de multidifusión.Leaves a multicast group.

EndReceive(IAsyncResult, IPEndPoint) EndReceive(IAsyncResult, IPEndPoint) EndReceive(IAsyncResult, IPEndPoint) EndReceive(IAsyncResult, IPEndPoint)

Finaliza una recepción asincrónica pendiente.Ends a pending asynchronous receive.

EndSend(IAsyncResult) EndSend(IAsyncResult) EndSend(IAsyncResult) EndSend(IAsyncResult)

Finaliza un envío asincrónico pendiente.Ends a pending asynchronous send.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determina si el objeto especificado es igual al objeto actual.Determines whether the specified object is equal to the current object.

(Inherited from Object)
Finalize() Finalize() Finalize() Finalize()
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Sirve como la función hash predeterminada.Serves as the default hash function.

(Inherited from Object)
GetType() GetType() GetType() GetType()

Obtiene el Type de la instancia actual.Gets the Type of the current instance.

(Inherited from Object)
JoinMulticastGroup(Int32, IPAddress) JoinMulticastGroup(Int32, IPAddress) JoinMulticastGroup(Int32, IPAddress) JoinMulticastGroup(Int32, IPAddress)

Agrega una clase UdpClient a un grupo de multidifusión.Adds a UdpClient to a multicast group.

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

Agrega una clase UdpClient a un grupo de multidifusión.Adds a UdpClient to a multicast group.

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

Agrega una clase UdpClient a un grupo de multidifusión con el período de vida (TTL) especificado.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)

Agrega una clase UdpClient a un grupo de multidifusión.Adds a UdpClient to a multicast group.

MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Crea una copia superficial del objeto Object actual.Creates a shallow copy of the current Object.

(Inherited from Object)
Receive(IPEndPoint) Receive(IPEndPoint) Receive(IPEndPoint) Receive(IPEndPoint)

Devuelve un datagrama UDP enviado por un host remoto.Returns a UDP datagram that was sent by a remote host.

ReceiveAsync() ReceiveAsync() ReceiveAsync() ReceiveAsync()

Devuelve de forma asincrónica un datagrama UDP enviado por un host remoto.Returns a UDP datagram asynchronously that was sent by a remote host.

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

Envía un datagrama UDP a un host remoto.Sends a UDP datagram to a remote host.

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

Envía un datagrama UDP al host en el extremo remoto especificado.Sends a UDP datagram to the host at the specified remote endpoint.

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

Envía un datagrama UDP a un puerto especificado, en un host remoto especificado.Sends a UDP datagram to a specified port on a specified remote host.

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

Envía un datagrama UDP a un host remoto de forma asincrónica.Sends a UDP datagram asynchronously to a remote host.

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

Envía un datagrama UDP a un host remoto de forma asincrónica.Sends a UDP datagram asynchronously to a remote host.

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

Envía un datagrama UDP a un host remoto de forma asincrónica.Sends a UDP datagram asynchronously to a remote host.

ToString() ToString() ToString() ToString()

Devuelve una cadena que representa el objeto actual.Returns a string that represents the current object.

(Inherited from Object)

Implementaciones de interfaz explícitas

IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose()

Libera todos los recursos que usa UdpClient.Releases all resources used by the UdpClient.

Seguridad

SocketPermission
Para establecer una conexión de salida o aceptar una solicitud entrante.To establish an outgoing connection or accept an incoming request.

Se aplica a

Consulte también: