EndReceive Method

UdpClient.EndReceive Method

Ends a pending asynchronous receive.

Namespace:  System.Net.Sockets
Assembly:  System (in System.dll)

public byte[] EndReceive(
	IAsyncResult asyncResult,
	ref IPEndPoint remoteEP
)

Parameters

asyncResult
Type: System.IAsyncResult
An IAsyncResult object returned by a call to BeginReceive.
remoteEP
Type: System.Net.IPEndPoint%
The specified remote endpoint.

Return Value

Type: System.Byte[]
If successful, the number of bytes received. If unsuccessful, this method returns 0.

ExceptionCondition
ArgumentNullException

asyncResult is null.

ArgumentException

asyncResult was not returned by a call to the BeginReceive method.

InvalidOperationException

EndReceive was previously called for the asynchronous read.

SocketException

An error occurred when attempting to access the underlying Socket. See the Remarks section for more information.

ObjectDisposedException

The underlying Socket has been closed.

This method blocks until the operation is complete.

To perform this operation synchronously, use the Receive method.

The following code example uses BeginSend to complete an asynchronous receive of a server response.


public static bool messageReceived = false;

public static void ReceiveCallback(IAsyncResult ar)
{
  UdpClient u = (UdpClient)((UdpState)(ar.AsyncState)).u;
  IPEndPoint e = (IPEndPoint)((UdpState)(ar.AsyncState)).e;

  Byte[] receiveBytes = u.EndReceive(ar, ref e);
  string receiveString = Encoding.ASCII.GetString(receiveBytes);

  Console.WriteLine("Received: {0}", receiveString);
  messageReceived = true;
}

public static void ReceiveMessages()
{
  // Receive a message and write it to the console.
  IPEndPoint e = new IPEndPoint(IPAddress.Any, listenPort);
  UdpClient u = new UdpClient(e);

  UdpState s = new UdpState();
  s.e = e;
  s.u = u;

  Console.WriteLine("listening for messages");
  u.BeginReceive(new AsyncCallback(ReceiveCallback), s);

  // Do some work while we wait for a message. For this example,
  // we'll just sleep
  while (!messageReceived)
  {
    Thread.Sleep(100);
  }
}


.NET Framework

Supported in: 4, 3.5, 3.0, 2.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Windows 7, Windows Vista SP1 or later, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008 (Server Core not supported), Windows Server 2008 R2 (Server Core supported with SP1 or later), Windows Server 2003 SP2

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Community Additions

ADD
Show:
© 2016 Microsoft