語言

UdpClient.Receive(IPEndPoint) 方法

定義

回傳由遠端主機傳送的 UDP 資料報。

public:
 cli::array <System::Byte> ^ Receive(System::Net::IPEndPoint ^ % remoteEP);
public byte[] Receive(ref System.Net.IPEndPoint? remoteEP);
public byte[] Receive(ref System.Net.IPEndPoint remoteEP);
member this.Receive : IPEndPoint -> byte[]
Public Function Receive (ByRef remoteEP As IPEndPoint) As Byte()

參數

remoteEP
IPEndPoint

a IPEndPoint 代表資料傳送的遠端主機。

傳回

Byte[]

一個包含資料報資料的陣 Byte 列。

例外狀況

標的 Socket 資產已經關閉。

存取該套接字時發生錯誤。

範例

以下範例示範此 Receive 方法。 該 Receive 方法會阻擋執行,直到收到訊息。 利用 IPEndPoint 傳遞到 Receive的 ,會揭示回應主機的身份。

 //Creates a UdpClient for reading incoming data.
 UdpClient receivingUdpClient = new UdpClient(11000);

 //Creates an IPEndPoint to record the IP Address and port number of the sender.
// The IPEndPoint will allow you to read datagrams sent from any source.
 IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
 try{

     // Blocks until a message returns on this socket from a remote host.
     Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);

     string returnData = Encoding.ASCII.GetString(receiveBytes);

     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());
 }
 catch ( Exception e ){
     Console.WriteLine(e.ToString());
 }
   'Creates a UdpClient for reading incoming data.
   Dim receivingUdpClient As New UdpClient(11000)
   
   'Creates an IPEndPoint to record the IP address and port number of the sender. 
   ' The IPEndPoint will allow you to read datagrams sent from any source.
   Dim RemoteIpEndPoint As New IPEndPoint(IPAddress.Any, 0)
   Try
      
      ' Blocks until a message returns on this socket from a remote host.
      Dim receiveBytes As [Byte]() = receivingUdpClient.Receive(RemoteIpEndPoint)
      
      Dim returnData As String = Encoding.ASCII.GetString(receiveBytes)
      
      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()))
   Catch e As Exception
      Console.WriteLine(e.ToString())
   End Try
End Sub

備註

此 Receive 方法會阻塞,直到遠端主機收到資料報。 當資料可用時,方法 Receive 會讀取第一個佇列的資料報,並將資料部分以位元組陣列的形式回傳。 此方法會 remoteEP 將參數填入 IPAddress 發送端的 和 埠號。

如果你在方法中 Connect 指定預設的遠端主機,該 Receive 方法只會接受該主機的資料報。 其他資料報都會被丟棄。

如果您收到 SocketException,請使用 SocketException.ErrorCode 以取得特定的錯誤代碼。 取得這些程式碼後,你可以參考 Windows Sockets 版本 2 的 API 錯誤程式碼 文件,了解錯誤的詳細說明。

Note

如果你打算接收多播資料報,請不要在呼叫Connect方法之前先呼叫該Receive方法。 你用來接收資料報的裝置 UdpClient 必須用多播埠號來建立。

適用於

另請參閱