Export (0) Print
Expand All

Socket.BeginSendTo Method

Sends data asynchronously to a specific remote host.

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

[HostProtectionAttribute(SecurityAction.LinkDemand, ExternalThreading = true)]
public IAsyncResult BeginSendTo(
	byte[] buffer,
	int offset,
	int size,
	SocketFlags socketFlags,
	EndPoint remoteEP,
	AsyncCallback callback,
	Object state
)

Parameters

buffer
Type: System.Byte[]

An array of type Byte that contains the data to send.

offset
Type: System.Int32

The zero-based position in buffer at which to begin sending data.

size
Type: System.Int32

The number of bytes to send.

socketFlags
Type: System.Net.Sockets.SocketFlags

A bitwise combination of the SocketFlags values.

remoteEP
Type: System.Net.EndPoint

An EndPoint that represents the remote device.

callback
Type: System.AsyncCallback

The AsyncCallback delegate.

state
Type: System.Object

An object that contains state information for this request.

Return Value

Type: System.IAsyncResult
An IAsyncResult that references the asynchronous send.

ExceptionCondition
ArgumentNullException

buffer is null.

-or-

remoteEP is null.

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.

NoteNote:

The HostProtectionAttribute attribute applied to this type or member has the following Resources property value: ExternalThreading. The HostProtectionAttribute does not affect desktop applications (which are typically started by double-clicking an icon, typing a command, or entering a URL in a browser). For more information, see the HostProtectionAttribute class or SQL Server Programming and Host Protection Attributes.

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 invoke 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 the Set method on a T:System.Threading.ManualResetEvent in the callback method when you want the original thread to continue executing. For additional information about 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. Use a port number of zero if you want the underlying service provider to select a free port. 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.

NoteNote:

If you receive a SocketException, use the SocketException.ErrorCode property to obtain the specific error code. After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation in the MSDN library for a detailed description of the error.

NoteNote:

This member outputs trace information when you enable network tracing in your application. For more information, see Network Tracing.

NoteNote:

The execution context (the security context, the impersonated user, and the calling context) is cached for the asynchronous Socket methods. After the first use of a particular context (a specific asynchronous Socket method, a specific Socket instance, and a specific callback), subsequent uses of that context will see a performance improvement.

The following code example asynchronously sends data to the specified remote host.

	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());
       }
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);
}

Windows 7, Windows Vista, Windows XP SP2, Windows XP Media Center Edition, Windows XP Professional x64 Edition, Windows XP Starter Edition, Windows Server 2008 R2, Windows Server 2008, Windows Server 2003, Windows Server 2000 SP4, Windows Millennium Edition, Windows 98, Windows CE, Windows Mobile for Smartphone, Windows Mobile for Pocket PC

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

.NET Framework

Supported in: 3.5, 3.0, 2.0, 1.1, 1.0

.NET Compact Framework

Supported in: 3.5, 2.0, 1.0

Community Additions

ADD
Show:
© 2014 Microsoft