UdpClient::BeginSend Method (array<Byte>^, Int32, IPEndPoint^, AsyncCallback^, Object^)

 

Sends a datagram to a destination asynchronously. The destination is specified by a EndPoint.

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

public:
[HostProtectionAttribute(SecurityAction::LinkDemand, ExternalThreading = true)]
IAsyncResult^ BeginSend(
	array<unsigned char>^ datagram,
	int bytes,
	IPEndPoint^ endPoint,
	AsyncCallback^ requestCallback,
	Object^ state
)

Parameters

datagram
Type: array<System::Byte>^

A Byte array that contains the data to be sent.

bytes
Type: System::Int32

The number of bytes to send.

endPoint
Type: System.Net::IPEndPoint^

The EndPoint that represents the destination for the data.

requestCallback
Type: System::AsyncCallback^

An AsyncCallback delegate that references the method to invoke when the operation is complete.

state
Type: System::Object^

A user-defined object that contains information about the send operation. This object is passed to the requestCallback delegate when the operation is complete.

Return Value

Type: System::IAsyncResult^

An IAsyncResult object that references the asynchronous send.

The asynchronous BeginSend operation must be completed by calling the EndSend method. Typically, the method is invoked by the requestCallback delegate.

This method does not block until the operation is complete. To block until the operation is complete, use one of the Send method overloads.

For detailed information about using the asynchronous programming model, see Calling Synchronous Methods Asynchronously.

The following code example uses BeginSend to asynchronously send a server request.

public:
    static bool isMessageSent;

    static void SendCallback(IAsyncResult^ asyncResult)
    {
        UdpClient^ udpClient = (UdpClient^)asyncResult->AsyncState;

        Console::WriteLine("number of bytes sent: {0}",
            udpClient->EndSend(asyncResult));
        isMessageSent = true;
    }
public:
    static void SendMessage2(String^ server, String^ message)
    {
        // create the udp socket
        UdpClient^ udpClient = gcnew UdpClient();
        array<Byte>^ sendBytes = Encoding::ASCII->GetBytes(message);

        // resolve the server name
        IPHostEntry^ resolvedServer = Dns::GetHostEntry(server);

        IPEndPoint^ ipEndPoint =
            gcnew IPEndPoint(resolvedServer->AddressList[0], listenPort);

        // send the message
        // the destination is defined by the IPEndPoint
        udpClient->BeginSend(sendBytes, sendBytes->Length, ipEndPoint,
            gcnew AsyncCallback(SendCallback), udpClient);

        // Do some work while we wait for the send to complete. For
        // this example, we'll just sleep
        while (!isMessageSent)
        {
            Thread::Sleep(100);
        }
    }

.NET Framework
Available since 2.0
Return to top
Show: