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

Объект IPEndPoint, представляющий удаленный узел, с которого выполняется передача данных.

Возвращаемое значение

Byte[]

Массив типа Byte, который содержит данные датаграммы.

Исключения

Основной объект Socket закрыт.

Произошла ошибка при обращении к сокету.

Примеры

В следующем примере демонстрируется Receive метод. Метод Receive блокирует выполнение, пока не получит сообщение. При использовании переданного IPEndPoint в Receiveотображается удостоверение отвечающего узла.

//Creates a UdpClient for reading incoming data.
UdpClient^ receivingUdpClient = gcnew 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 = gcnew IPEndPoint( IPAddress::Any,0 );
try
{
   // Blocks until a message returns on this socket from a remote host.
   array<Byte>^receiveBytes = receivingUdpClient->Receive(  RemoteIpEndPoint );

   String^ returnData = Encoding::ASCII->GetString( receiveBytes );

   Console::WriteLine( "This is the message you received {0}", returnData );
   Console::WriteLine( "This message was sent from {0} on their port number {1}",
      RemoteIpEndPoint->Address, RemoteIpEndPoint->Port );
}
catch ( Exception^ e ) 
{
   Console::WriteLine( e->ToString() );
}
 //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 для получения определенного кода ошибки. Получив этот код, вы можете обратиться к документации по коду ошибки API сокетов Windows версии 2 , чтобы получить подробное описание ошибки.

Примечание

Если вы планируете получать многоадресные датаграммы, не вызывайте Connect метод перед вызовом Receive метода . Объект, используемый UdpClient для получения датаграмм, должен быть создан с использованием номера порта многоадресной рассылки.

Применяется к

См. также раздел