Information
The topic you requested is included in another documentation set. For convenience, it's displayed below. Choose Switch to see the topic in its original location.

Socket.BeginSendTo Method

Sends data asynchronously to a specific remote host.

[Visual Basic]
Public Function BeginSendTo( _
   ByVal buffer() As Byte, _
   ByVal offset As Integer, _
   ByVal size As Integer, _
   ByVal socketFlags As SocketFlags, _
   ByVal remoteEP As EndPoint, _
   ByVal callback As AsyncCallback, _
   ByVal state As Object _
) As IAsyncResult
[C#]
public IAsyncResult BeginSendTo(
 byte[] buffer,
 int offset,
 int size,
 SocketFlags socketFlags,
 EndPoint remoteEP,
 AsyncCallback callback,
 object state
);
[C++]
public: IAsyncResult* BeginSendTo(
 unsigned char buffer __gc[],
 int offset,
 int size,
 SocketFlags socketFlags,
 EndPoint* remoteEP,
 AsyncCallback* callback,
 Object* state
);
[JScript]
public function BeginSendTo(
   buffer : Byte[],
 offset : int,
 size : int,
 socketFlags : SocketFlags,
 remoteEP : EndPoint,
 callback : AsyncCallback,
 state : Object
) : IAsyncResult;

Parameters

buffer
An array of type Byte that contains the data to send.
offset
The zero-based position in buffer at which to begin sending data.
size
The number of bytes to send.
socketFlags
A bitwise combination of the SocketFlags values.
remoteEP
An EndPoint that represents the remote device.
callback
The AsyncCallback delegate.
state
An object containing state information for this request.

Return Value

An IAsyncResult that references the asynchronous send.

Exceptions

Exception Type Condition
ArgumentNullException buffer is a null reference (Nothing in Visual Basic).

-or-

remoteEP is a null reference (Nothing).

SocketException An error occurred when attempting to access the socket. See the Remarks section for more information.
ArgumentOutOfRangeException offset is less than 0.

-or-

offset is greater than the length of buffer.

-or-

size is less than 0.

-or-

size is greater than the length of buffer minus the value of the offset parameter.

ObjectDisposedException The Socket has been closed.
SecurityException A caller higher in the call stack does not have permission for the requested operation.

Remarks

The BeginSendTo method starts an asynchronous send operation to the remote host specified in the remoteEP parameter. Calling the BeginSendTo method gives you the ability to send data within a separate execution thread. Although intended for connectionless protocols, BeginSendTo works with both connectionless and connection-oriented protocols.

You can create a callback method that implements the AsyncCallback delegate and pass its name to the BeginSendTo method. To do this, at the very minimum, your state parameter must contain the connected or default Socket being used for communication. If your callback needs more information, you can create a small class to hold the Socket, and the other required information. Pass an instance of this class to the BeginSendTo method through the state parameter.

Your callback method should implement the EndSendTo method. When your application calls BeginSendTo, the system will use a separate thread to execute the specified callback method, and will block on EndSendTo until the Socket sends the number of bytes requested or throws an exception. If you want the original thread to block after you call the BeginSendTo method, use the WaitHandle.WaitOne method. Call ManualResetEvent.Set in the callback method when you want the original thread to continue executing. For additional information on writing callback methods see Callback Sample.

If you are using a connection-oriented protocol, you must first call the Connect, BeginConnect, Accept, or BeginAccept method, or BeginSendTo will throw a SocketException. BeginSendTo will ignore the remoteEP parameter and send data to the EndPoint established in the Connect, BeginConnect, Accept, or BeginAccept method.

If you are using a connectionless protocol, you do not need to establish a default remote host with the Connect or BeginConnect method prior to calling SendTo. You only need to do this if you intend to call the BeginSend method. If you do call the Connect or BeginConnect method prior to calling SendTo, the remoteEP parameter will override the specified default remote host for that send operation only. You are also not required to call the Bind method. In this case, the underlying service provider will assign the most appropriate local network address and port number. If you need to identify the assigned local network address and port number, you can use the LocalEndPoint property after the EndSendTo method successfully completes.

If you want to send data to a broadcast address, you must first call the SetSocketOption method and set the socket option to SocketOptionName.Broadcast. -You must also be sure that the size of your buffer does not exceed the maximum packet size of the underlying service provider. If it does, the datagram will not be sent and EndSendTo will throw a SocketException.

If you specify the DontRoute flag as the socketflags parameter, the data you are sending will not be routed. If you specify the OutOfBand flag as the socketflags parameter, only out-of-band (OOB) data is sent. The OOB data is a logically independent transmission channel associated with each pair of connected stream sockets. This data is delivered with higher priority and independently of the normal data.

Note   If you receive a SocketException, use SocketException.ErrorCode to obtain the specific error code. Once you have obtained this code, you can refer to the Windows Socket Version 2 API error code documentation in MSDN for a detailed description of the error.

Example

[Visual Basic, C#, C++] The following example asynchronously sends data to the specified remote host.

[Visual Basic] 
Dim lipa As IPHostEntry = Dns.Resolve("host.contoso.com")
Dim lep As New IPEndPoint(lipa.AddressList(0), 11000)

Dim s As New Socket(lep.Address.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
Try
   
   While True
      allDone.Reset()
      
      Dim buff As Byte() = Encoding.ASCII.GetBytes("This is a test")
      
      Console.WriteLine("Sending Message Now..")
      s.BeginSendTo(buff, 0, buff.Length, 0, lep, New AsyncCallback(AddressOf Async_Send_Receive.SendTo_Callback), s)
      
      allDone.WaitOne()
   End While
Catch e As Exception
   Console.WriteLine(e.ToString())
End Try
   End Sub 'SendTo

[C#] 
IPHostEntry lipa = Dns.Resolve("host.contoso.com");
IPEndPoint lep = new IPEndPoint(lipa.AddressList[0], 11000);

   Socket s = new Socket(lep.Address.AddressFamily,
                                  SocketType.Stream,
                                     ProtocolType.Tcp);
   try{
      
             while(true){
             allDone.Reset();

             byte[] buff = Encoding.ASCII.GetBytes("This is a test");
             
             Console.WriteLine("Sending Message Now..");
             s.BeginSendTo(buff, 0, buff.Length, 0, lep, new AsyncCallback(Async_Send_Receive.SendTo_Callback), s);

             allDone.WaitOne();
        }
   }
   catch (Exception e){
        Console.WriteLine(e.ToString());
   }

[C++] 
IPHostEntry* lipa = Dns::Resolve(S"host.contoso.com");
IPEndPoint* lep = new IPEndPoint(lipa->AddressList[0], 11000);

Socket* s = new Socket(lep->Address->AddressFamily,
    SocketType::Stream,
    ProtocolType::Tcp);

try {
    while(true){
        allDone->Reset();

        Byte buff[] = Encoding::ASCII->GetBytes(S"This is a test");

        Console::WriteLine(S"Sending Message Now..");
        AsyncCallback* pasync = new AsyncCallback(0, &Async_Send_Receive::SendTo_Callback);
        s->BeginSendTo(buff, 0, buff->Length, SocketFlags::None, lep,
            pasync, s);

        allDone->WaitOne();
    }
} catch (Exception* e) {
    Console::WriteLine(e);
}

[JScript] No example is available for JScript. To view a Visual Basic, C#, or C++ example, click the Language Filter button Language Filter in the upper-left corner of the page.

Requirements

Platforms: Windows 98, Windows NT 4.0, Windows Millennium Edition, Windows 2000, Windows XP Home Edition, Windows XP Professional, Windows Server 2003 family, .NET Compact Framework, Common Language Infrastructure (CLI) Standard

See Also

Socket Class | Socket Members | System.Net.Sockets Namespace | Including Asynchronous Calls | Callback Sample | EndSendTo | AsyncCallback | Connect | LocalEndPoint | Broadcast | SetSocketOption

Was this page helpful?
(1500 characters remaining)
Thank you for your feedback
Show:
© 2015 Microsoft