UdpClient 類別

定義

提供使用者資料包通訊協定 (User Datagram Protocol,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
實作

範例

下列範例會使用埠UdpClient 11000 上的主機名稱www.contoso.com來建立連接。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. 使用傳遞至Receive的時,會顯示回應主機的身分識別。 IPEndPointUsing 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.

注意

請勿使用主機Send名呼叫,或IPEndPoint如果您已經指定預設的遠端主機。Do 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. 使用方法來UdpClient訂閱多播群組。 JoinMulticastGroupUse the JoinMulticastGroup method to subscribe a UdpClient to a multicast group. 使用方法, UdpClient從多播群組取消訂閱。 DropMulticastGroupUse 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 是否允許將網際網路通訊協定 (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 傳送之網際網路通訊協定 (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 所使用的 Unmanaged 資源,並選擇性地釋放 Managed 資源。Releases the unmanaged resources used by the UdpClient and optionally releases the managed resources.

DropMulticastGroup(IPAddress)

保留多點傳送 (Multicast) 群組。Leaves a multicast group.

DropMulticastGroup(IPAddress, Int32)

保留多點傳送 (Multicast) 群組。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)

使用指定的存活時間 (Time to Live,TTL) 將 UdpClient 加入至多點傳送群組。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 的淺層複本 (Shallow Copy)。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()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)

明確介面實作

IDisposable.Dispose()

釋放 UdpClient 所使用的所有資源。Releases all resources used by the UdpClient.

安全性

SocketPermission
建立連出連線或接受傳入要求。To establish an outgoing connection or accept an incoming request.

適用於

另請參閱