Socket.BeginSendTo(Byte[], Int32, Int32, SocketFlags, EndPoint, AsyncCallback, Object) Socket.BeginSendTo(Byte[], Int32, Int32, SocketFlags, EndPoint, AsyncCallback, Object) Socket.BeginSendTo(Byte[], Int32, Int32, SocketFlags, EndPoint, AsyncCallback, Object) Socket.BeginSendTo(Byte[], Int32, Int32, SocketFlags, EndPoint, AsyncCallback, Object) Method

定义

以异步方式将数据发送到特定远程主机。Sends data asynchronously to a specific remote host.

public:
 IAsyncResult ^ BeginSendTo(cli::array <System::Byte> ^ buffer, int offset, int size, System::Net::Sockets::SocketFlags socket_flags, System::Net::EndPoint ^ remote_end, AsyncCallback ^ callback, System::Object ^ state);
public IAsyncResult BeginSendTo (byte[] buffer, int offset, int size, System.Net.Sockets.SocketFlags socket_flags, System.Net.EndPoint remote_end, AsyncCallback callback, object state);
member this.BeginSendTo : byte[] * int * int * System.Net.Sockets.SocketFlags * System.Net.EndPoint * AsyncCallback * obj -> IAsyncResult
Public Function BeginSendTo (buffer As Byte(), offset As Integer, size As Integer, socket_flags As SocketFlags, remote_end As EndPoint, callback As AsyncCallback, state As Object) As IAsyncResult

参数

buffer
Byte[]

Byte 类型的数组,它包含要发送的数据。An array of type Byte that contains the data to send.

offset
Int32 Int32 Int32 Int32

buffer 中的从其开始发送数据的、从零开始编排的位置。The zero-based position in buffer at which to begin sending data.

size
Int32 Int32 Int32 Int32

要发送的字节数。The number of bytes to send.

socketFlags
SocketFlags SocketFlags SocketFlags SocketFlags

SocketFlags 值的按位组合。A bitwise combination of the SocketFlags values.

remoteEP
EndPoint EndPoint EndPoint EndPoint

表示远程设备的 EndPointAn EndPoint that represents the remote device.

state
Object Object Object Object

一个对象,它包含此请求的状态信息。An object that contains state information for this request.

返回

引用异步发送的 IAsyncResultAn IAsyncResult that references the asynchronous send.

异常

buffernullbuffer is null.

- 或 --or- remoteEPnullremoteEP is null.

尝试访问套接字时出错。An error occurred when attempting to access the socket.

offset 小于 0。offset is less than 0.

- 或 --or- offset 大于 buffer 的长度。offset is greater than the length of buffer.

- 或 --or- size 小于 0。size is less than 0.

- 或 --or- size 大于 buffer 的长度减去 offset 参数的值。size is greater than the length of buffer minus the value of the offset parameter.

调用堆栈中的较高调用方无权执行所请求的操作。A caller higher in the call stack does not have permission for the requested operation.

示例

下面的代码示例以异步方式将数据发送到指定的远程主机。The following code example asynchronously sends data to the specified remote host.

IPHostEntry^ lipa = Dns::Resolve( "host.contoso.com" );
IPEndPoint^ lep = gcnew IPEndPoint( lipa->AddressList[ 0 ], 11000 );

Socket^ s = gcnew Socket( lep->Address->AddressFamily,
   SocketType::Stream,
   ProtocolType::Tcp );
try
{
   while ( true )
   {
      allDone->Reset();

      array<Byte>^ buff = Encoding::ASCII->GetBytes( "This is a test" );

      Console::WriteLine( "Sending Message Now.." );
      s->BeginSendTo( buff, 0, buff->Length, SocketFlags::None, lep,
         gcnew AsyncCallback( &Async_Send_Receive::Connect_Callback ), s );

      allDone->WaitOne();
   }
}
catch ( Exception^ e ) 
{
   Console::WriteLine( e );
}
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());
      }
   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

注解

BeginSendTo方法启动异步发送操作中指定的远程主机到remoteEP参数。The BeginSendTo method starts an asynchronous send operation to the remote host specified in the remoteEP parameter. 调用BeginSendTo方法使你能够发送单独的执行线程中的数据。Calling the BeginSendTo method gives you the ability to send data within a separate execution thread. 适用于无连接协议,尽管BeginSendTo适用于无连接和面向连接的协议。Although intended for connectionless protocols, BeginSendTo works with both connectionless and connection-oriented protocols.

可以创建实现一个回调方法AsyncCallback委托并将传递到其名称BeginSendTo方法。You can create a callback method that implements the AsyncCallback delegate and pass its name to the BeginSendTo method. 为此,至少,你state参数必须包含已连接或默认Socket正用于通信。To do this, at the very minimum, your state parameter must contain the connected or default Socket being used for communication. 如果回调需要详细信息,可以创建一个小类来保存Socket,和其他所需的信息。If your callback needs more information, you can create a small class to hold the Socket, and the other required information. 传递到此类的实例BeginSendTo方法通过state参数。Pass an instance of this class to the BeginSendTo method through the state parameter.

回调方法应该调用EndSendTo方法。Your callback method should invoke the EndSendTo method. 当应用程序调用BeginSendTo,系统将使用一个单独的线程来执行指定的回调方法,并阻止EndSendTo直到Socket发送请求的字节数或引发异常。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. 如果你想要阻止调用后的原始线程BeginSendTo方法,请使用WaitHandle.WaitOne方法。If you want the original thread to block after you call the BeginSendTo method, use the WaitHandle.WaitOne method. 当你想要继续执行的原始线程时请在回调方法调用 Set 方法。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 Marshaling a Delegate as a Callback Method.

如果使用的是面向连接的协议,必须首先调用ConnectBeginConnectAccept,或BeginAccept方法,或BeginSendTo将引发SocketExceptionIf 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 将忽略remoteEP参数并将数据发送到EndPoint中建立ConnectBeginConnectAccept,或BeginAccept方法。BeginSendTo will ignore the remoteEP parameter and send data to the EndPoint established in the Connect, BeginConnect, Accept, or BeginAccept method.

如果使用的是无连接协议,不需要建立默认远程主机使用ConnectBeginConnect方法之前调用SendToIf 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. 只需执行此操作,如果你想要调用BeginSend方法。You only need to do this if you intend to call the BeginSend method. 如果调用ConnectBeginConnect方法,然后调用SendTo,则remoteEP参数将替代指定的默认远程主机,只为发送操作。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. 也不需要调用Bind方法。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. 如果你想要选择可用端口的基础服务提供程序,请使用端口号 0。Use a port number of zero if you want the underlying service provider to select a free port. 如果你需要标识分配的本地网络地址和端口号,则可以使用LocalEndPoint属性后的EndSendTo方法成功完成。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.

如果你想要将数据发送到的广播地址,则必须首先调用SetSocketOption方法,设置套接字选项设为SocketOptionName.BroadcastIf 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. 如果是这样,将不发送数据报并EndSendTo将引发SocketExceptionIf it does, the datagram will not be sent and EndSendTo will throw a SocketException.

如果指定DontRoute标记为socketflags参数,不会将路由发送的数据。If you specify the DontRoute flag as the socketflags parameter, the data you are sending will not be routed.

备注

如果你收到SocketException,使用SocketException.ErrorCode属性来获取特定错误代码。If you receive a SocketException, use the SocketException.ErrorCode property to obtain the specific error code. 获取此代码后,请参阅Windows 套接字版本 2 API 错误代码有关错误的详细说明的文档。After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation for a detailed description of the error.

备注

当你在应用程序中启用网络跟踪后,此成员将输出跟踪信息。This member outputs trace information when you enable network tracing in your application. 有关详细信息,请参阅在.NET Framework 中进行网络跟踪For more information, see Network Tracing in the .NET Framework.

备注

为异步缓存的执行上下文 (的安全上下文中,被模拟的用户,并在调用上下文)Socket方法。The execution context (the security context, the impersonated user, and the calling context) is cached for the asynchronous Socket methods. 后首次使用特定的上下文 (特定于异步Socket方法中,特定Socket实例和特定的回调),以后使用该上下文将看到性能的改进。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.

适用于

另请参阅