UdpClient 类

定义

提供用户数据报协议 (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
继承
UdpClient
实现

示例

以下示例使用端口11000上的主机名 www.contoso.com 建立 UdpClient 连接。The following example establishes a UdpClient connection using the host name www.contoso.com on port 11000. 小型字符串消息将发送到两个单独的远程主机。A small string message is sent to two separate remote host machines. Receive 方法阻止执行,直到收到消息。The Receive method blocks execution until a message is received. 使用传递给 ReceiveIPEndPoint 将显示响应主机的标识。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 

注解

UdpClient 类提供了在阻止同步模式下发送和接收无连接 UDP 数据报的简单方法。The UdpClient class provides simple methods for sending and receiving connectionless UDP datagrams in blocking synchronous mode. 由于 UDP 是一种无连接的传输协议,因此在发送和接收数据之前,无需建立远程主机连接。Because UDP is a connectionless transport protocol, you do not need to establish a remote host connection prior to sending and receiving data. 不过,您可以通过以下两种方式之一来建立默认远程主机的选项:You do, however, have the option of establishing a default remote host in one of the following two ways:

  • 使用远程主机名和端口号作为参数创建 UdpClient 类的实例。Create an instance of the UdpClient class using the remote host name and port number as parameters.

  • 创建 UdpClient 类的实例,然后调用 Connect 方法。Create an instance of the UdpClient class and then call the Connect method.

你可以使用 UdpClient 中提供的任何发送方法将数据发送到远程设备。You can use any of the send methods provided in the UdpClient to send data to a remote device. 使用 Receive 方法从远程主机接收数据。Use the Receive method to receive data from remote hosts.

备注

如果已指定默认远程主机,请不要使用主机名或 IPEndPoint 调用 SendDo not call Send using a host name or IPEndPoint if you have already specified a default remote host. 如果这样做,UdpClient 会引发异常。If you do, UdpClient will throw an exception.

利用 UdpClient 方法,还可以发送和接收多播数据报。UdpClient methods also allow you to send and receive multicast datagrams. 使用 JoinMulticastGroup 方法将 UdpClient 订阅到多播组。Use the JoinMulticastGroup method to subscribe a UdpClient to a multicast group. 使用 DropMulticastGroup 方法从多播组取消订阅 UdpClientUse the DropMulticastGroup method to unsubscribe a UdpClient from a multicast group.

构造函数

UdpClient()

初始化 UdpClient 类的新实例。Initializes a new instance of the UdpClient class.

UdpClient(AddressFamily)

初始化 UdpClient 类的新实例。Initializes a new instance of the UdpClient class.

UdpClient(Int32)

初始化 UdpClient 类的新实例,并将它绑定到所提供的本地端口号。Initializes a new instance of the UdpClient class and binds it to the local port number provided.

UdpClient(Int32, AddressFamily)

初始化 UdpClient 类的新实例,并将它绑定到所提供的本地端口号。Initializes a new instance of the UdpClient class and binds it to the local port number provided.

UdpClient(IPEndPoint)

初始化 UdpClient 类的新实例,并将其绑定到指定的本地终结点。Initializes a new instance of the UdpClient class and binds it to the specified local endpoint.

UdpClient(String, Int32)

初始化 UdpClient 类的新实例,并建立默认远程主机。Initializes a new instance of the UdpClient class and establishes a default remote host.

属性

Active

获取或设置一个值,该值指示是否已建立默认远程主机。Gets or sets a value indicating whether a default remote host has been established.

Available

获取从网络接收的可读取的数据量。Gets the amount of data received from the network that is available to read.

Client

获取或设置基础网络 SocketGets or sets the underlying network Socket.

DontFragment

获取或设置 Boolean 值,该值指定 UdpClient 是否允许将 Internet 协议 (IP) 数据报分段。Gets or sets a Boolean value that specifies whether the UdpClient allows Internet Protocol (IP) datagrams to be fragmented.

EnableBroadcast

获取或设置 Boolean 值,该值指定 UdpClient 是否可以发送或接收广播数据包。Gets or sets a Boolean value that specifies whether the UdpClient may send or receive broadcast packets.

ExclusiveAddressUse

获取或设置 Boolean 值,指定 UdpClient 是否只允许一个客户端使用端口。Gets or sets a Boolean value that specifies whether the UdpClient allows only one client to use a port.

MulticastLoopback

获取或设置 Boolean 值,该值指定是否将输出多播数据包传递给发送应用程序。Gets or sets a Boolean value that specifies whether outgoing multicast packets are delivered to the sending application.

Ttl

获取或设置一个值,它指定由 UdpClient 发送的 Internet 协议 (IP) 数据包的生存时间 (TTL)。Gets or sets a value that specifies the Time to Live (TTL) value of Internet Protocol (IP) packets sent by the UdpClient.

方法

AllowNatTraversal(Boolean)

启用或禁用针对 UdpClient 实例的网络地址转换 (NAT) 遍历。Enables or disables Network Address Translation (NAT) traversal on a UdpClient instance.

BeginReceive(AsyncCallback, Object)

从远程主机异步接收数据报。Receives a datagram from a remote host asynchronously.

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

将数据报异步发送到远程主机。Sends a datagram to a remote host asynchronously. 先前已通过调用 Connect 指定目标。The destination was specified previously by a call to Connect.

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

将数据报异步发送到目标。Sends a datagram to a destination asynchronously. 目标由 EndPoint 指定。The destination is specified by a EndPoint.

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

将数据报异步发送到目标。Sends a datagram to a destination asynchronously. 目标由主机名和端口号指定。The destination is specified by the host name and port number.

Close()

关闭 UDP 连接。Closes the UDP connection.

Connect(IPAddress, Int32)

使用指定的 IP 地址和端口号建立默认远程主机。Establishes a default remote host using the specified IP address and port number.

Connect(IPEndPoint)

使用指定的网络终结点建立默认远程主机。Establishes a default remote host using the specified network endpoint.

Connect(String, Int32)

使用指定的主机名和端口号建立默认远程主机。Establishes a default remote host using the specified host name and port number.

Dispose()

释放由 UdpClient 占用的托管和非托管资源。Releases the managed and unmanaged resources used by the UdpClient.

Dispose(Boolean)

释放由 UdpClient 占用的非托管资源,还可以另外再释放托管资源。Releases the unmanaged resources used by the UdpClient and optionally releases the managed resources.

DropMulticastGroup(IPAddress)

退出多播组。Leaves a multicast group.

DropMulticastGroup(IPAddress, Int32)

退出多播组。Leaves a multicast group.

EndReceive(IAsyncResult, IPEndPoint)

结束挂起的异步接收。Ends a pending asynchronous receive.

EndSend(IAsyncResult)

结束挂起的异步发送。Ends a pending asynchronous send.

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
Finalize()
GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
JoinMulticastGroup(Int32, IPAddress)

UdpClient 添加到多播组。Adds a UdpClient to a multicast group.

JoinMulticastGroup(IPAddress)

UdpClient 添加到多播组。Adds a UdpClient to a multicast group.

JoinMulticastGroup(IPAddress, Int32)

UdpClient 添加到具有指定生存时间 (TTL) 的多播组。Adds a UdpClient to a multicast group with the specified Time to Live (TTL).

JoinMulticastGroup(IPAddress, IPAddress)

UdpClient 添加到多播组。Adds a UdpClient to a multicast group.

MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
Receive(IPEndPoint)

返回由远程主机发送的 UDP 数据报。Returns a UDP datagram that was sent by a remote host.

ReceiveAsync()

异步返回由远程主机发送的 UDP 数据报。Returns a UDP datagram asynchronously that was sent by a remote host.

Send(Byte[], Int32)

将 UDP 数据报发送到远程主机。Sends a UDP datagram to a remote host.

Send(Byte[], Int32, IPEndPoint)

将 UDP 数据报发送到位于指定远程终结点的主机。Sends a UDP datagram to the host at the specified remote endpoint.

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

将 UDP 数据报发送到指定远程主机上的指定端口。Sends a UDP datagram to a specified port on a specified remote host.

SendAsync(Byte[], Int32)

将 UDP 数据报异步发送到远程主机。Sends a UDP datagram asynchronously to a remote host.

SendAsync(Byte[], Int32, IPEndPoint)

将 UDP 数据报异步发送到远程主机。Sends a UDP datagram asynchronously to a remote host.

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

将 UDP 数据报异步发送到远程主机。Sends a UDP datagram asynchronously to a remote host.

ToString()

返回一个表示当前对象的 string。Returns a string that represents the current object.

(继承自 Object)

显式接口实现

IDisposable.Dispose()

释放由 UdpClient 使用的所有资源。Releases all resources used by the UdpClient.

适用于

另请参阅