Socket.BeginAccept Socket.BeginAccept Socket.BeginAccept Socket.BeginAccept Method

定义

开始一个异步操作来接受一个传入的连接尝试。Begins an asynchronous operation to accept an incoming connection attempt.

重载

BeginAccept(AsyncCallback, Object) BeginAccept(AsyncCallback, Object) BeginAccept(AsyncCallback, Object) BeginAccept(AsyncCallback, Object)

开始一个异步操作来接受一个传入的连接尝试。Begins an asynchronous operation to accept an incoming connection attempt.

BeginAccept(Int32, AsyncCallback, Object) BeginAccept(Int32, AsyncCallback, Object) BeginAccept(Int32, AsyncCallback, Object) BeginAccept(Int32, AsyncCallback, Object)

开始异步操作以接受传入的连接尝试并接收客户端应用程序发送的第一个数据块。Begins an asynchronous operation to accept an incoming connection attempt and receives the first block of data sent by the client application.

BeginAccept(Socket, Int32, AsyncCallback, Object) BeginAccept(Socket, Int32, AsyncCallback, Object) BeginAccept(Socket, Int32, AsyncCallback, Object) BeginAccept(Socket, Int32, AsyncCallback, Object)

开始异步操作以接受从指定套接字传入的连接尝试并接收客户端应用程序发送的第一个数据块。Begins an asynchronous operation to accept an incoming connection attempt from a specified socket and receives the first block of data sent by the client application.

BeginAccept(AsyncCallback, Object) BeginAccept(AsyncCallback, Object) BeginAccept(AsyncCallback, Object) BeginAccept(AsyncCallback, Object)

开始一个异步操作来接受一个传入的连接尝试。Begins an asynchronous operation to accept an incoming connection attempt.

public:
 IAsyncResult ^ BeginAccept(AsyncCallback ^ callback, System::Object ^ state);
public IAsyncResult BeginAccept (AsyncCallback callback, object state);
member this.BeginAccept : AsyncCallback * obj -> IAsyncResult
Public Function BeginAccept (callback As AsyncCallback, state As Object) As IAsyncResult

参数

state
Object Object Object Object

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

返回

一个 IAsyncResult,它引用异步 Socket 创建。An IAsyncResult that references the asynchronous Socket creation.

异常

此方法需要 Windows NT。Windows NT is required for this method.

正在接受的套接字不会侦听连接。The accepting socket is not listening for connections. 在调用 Bind(EndPoint) 之前必须调用 Listen(Int32)BeginAccept(AsyncCallback, Object)You must call Bind(EndPoint) and Listen(Int32) before calling BeginAccept(AsyncCallback, Object).

- 或 --or- 已接受的套接字是绑定的。The accepted socket is bound.

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

示例

下面的代码示例尝试以异步方式接收传入连接。The following code example attempts to receive an incoming connection asynchronously.

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
{
   s->Bind( lep );
   s->Listen( 1000 );

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

      Console::WriteLine( "Waiting for a connection..." );
      s->BeginAccept( 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{
           s.Bind(lep);
           s.Listen(1000);

           while(true){
                allDone.Reset();

                Console.WriteLine("Waiting for a connection...");
                s.BeginAccept(new AsyncCallback(Async_Send_Receive.Listen_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
      s.Bind(lep)
      s.Listen(1000)
      
      While True
         allDone.Reset()
         
         Console.WriteLine("Waiting for a connection...")
         s.BeginAccept(New AsyncCallback(AddressOf Async_Send_Receive.Listen_Callback), s)
         
         allDone.WaitOne()
      End While
   Catch e As Exception
      Console.WriteLine(e.ToString())
   End Try
End Sub 'Listen

注解

可以使用面向连接的协议BeginAccept方法以异步处理传入的连接尝试。Connection-oriented protocols can use the BeginAccept method to asynchronously process incoming connection attempts. 以异步方式接受连接使你能够发送和接收单独的执行线程中的数据。Accepting connections asynchronously gives you the ability to send and receive data within a separate execution thread. 然后再调用BeginAccept方法时,必须调用Listen方法来侦听并对传入连接请求进行排队。Before calling the BeginAccept method, you must call the Listen method to listen for and queue incoming connection requests.

必须创建实现一个回调方法AsyncCallback委托并将传递到其名称BeginAccept方法。You must create a callback method that implements the AsyncCallback delegate and pass its name to the BeginAccept method. 为此,请在最低限度下,必须通过侦听Socket对象传递给BeginAccept通过state参数。To do this, at the very minimum, you must pass the listening Socket object to BeginAccept through the state parameter. 如果回调需要详细信息,可以创建一个小类来保存Socket和其他所需的信息。If your callback needs more information, you can create a small class to hold the Socket and the other required information. 传递到此类的实例BeginAccept方法通过state参数。Pass an instance of this class to the BeginAccept method through the state parameter.

回调方法应该调用EndAccept方法。Your callback method should invoke the EndAccept method. 当应用程序调用BeginAccept,系统通常使用一个单独的线程来执行指定的回调方法,并阻止上EndAccept直到检索到挂起的连接。When your application calls BeginAccept, the system usually uses a separate thread to execute the specified callback method and blocks on EndAccept until a pending connection is retrieved. EndAccept 将返回一个新Socket对象可用于发送和接收数据与远程主机。EndAccept will return a new Socket object that you can use to send and receive data with the remote host. 不能使用此返回Socket为接受任何其他连接的连接队列。You cannot use this returned Socket to accept any additional connections from the connection queue. 如果你想要阻止调用后的原始线程BeginAccept方法,请使用WaitHandle.WaitOneIf you want the original thread to block after you call the BeginAccept method, use WaitHandle.WaitOne. 在调用 Set 方法ManualResetEvent在回调方法时所需的原始线程继续执行。Call the Set method on a ManualResetEvent in the callback method when you want the original thread to continue executing.

系统还可能使用调用线程来调用该回调方法。The system may also use the calling thread to invoke the callback method. 在这种情况下,CompletedSynchronously对返回的属性IAsyncResult会将设置为指示BeginAccept方法以同步方式完成。In this case, the CompletedSynchronously property on the returned IAsyncResult will be set to indicate that the BeginAccept method completed synchronously.

编写回调方法的其他信息,请参阅委托作为回调方法进行封送For additional information on writing callback methods see Marshaling a Delegate as a Callback Method.

若要取消挂起调用BeginAccept方法,关闭SocketTo cancel a pending call to the BeginAccept method, close the Socket. Close回调的异步操作正在进行中时,调用方法,提供给BeginAccept调用方法。When the Close method is called while an asynchronous operation is in progress, the callback provided to the BeginAccept method is called. 随后调用EndAccept方法将引发ObjectDisposedException以指示已取消该操作。A subsequent call to the EndAccept method will throw an ObjectDisposedException to indicate that the operation has been cancelled.

备注

可以使用RemoteEndPoint属性所返回的Socket来标识远程主机的网络地址和端口号。You can use the RemoteEndPoint property of the returned Socket to identify the remote host's network address and port number.

备注

如果你收到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.

另请参阅

BeginAccept(Int32, AsyncCallback, Object) BeginAccept(Int32, AsyncCallback, Object) BeginAccept(Int32, AsyncCallback, Object) BeginAccept(Int32, AsyncCallback, Object)

开始异步操作以接受传入的连接尝试并接收客户端应用程序发送的第一个数据块。Begins an asynchronous operation to accept an incoming connection attempt and receives the first block of data sent by the client application.

public:
 IAsyncResult ^ BeginAccept(int receiveSize, AsyncCallback ^ callback, System::Object ^ state);
public IAsyncResult BeginAccept (int receiveSize, AsyncCallback callback, object state);
member this.BeginAccept : int * AsyncCallback * obj -> IAsyncResult
Public Function BeginAccept (receiveSize As Integer, callback As AsyncCallback, state As Object) As IAsyncResult

参数

receiveSize
Int32 Int32 Int32 Int32

要从发送方读取的字节数。The number of bytes to accept from the sender.

state
Object Object Object Object

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

返回

一个 IAsyncResult,它引用异步 Socket 创建。An IAsyncResult that references the asynchronous Socket creation.

异常

此方法需要 Windows NT。Windows NT is required for this method.

正在接受的套接字不会侦听连接。The accepting socket is not listening for connections. 在调用 Bind(EndPoint) 之前必须调用 Listen(Int32)BeginAccept(AsyncCallback, Object)You must call Bind(EndPoint) and Listen(Int32) before calling BeginAccept(AsyncCallback, Object).

- 或 --or- 已接受的套接字是绑定的。The accepted socket is bound.

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

示例

下面的代码示例打开一个套接字并接受异步连接。The following code example opens a socket and accepts an asynchronous connection. 在此示例中,套接字接受前 10 个字节的数据。In this example, the socket accepts the initial 10 bytes of data. 接收的字节数和数据的回调委托显示在控制台上。The number of bytes received and the data are displayed on the console by the callback delegate. 请参阅BeginReceive如何接收剩余数据的说明。See BeginReceive for a description of how the remaining data is received.

   // This server waits for a connection and then uses asynchronous operations to
   // accept the connection with initial data sent from the client.
   // Establish the local endpoint for the socket.
   IPHostEntry^ ipHostInfo = Dns::GetHostEntry( Dns::GetHostName() );
   IPAddress^ ipAddress = ipHostInfo->AddressList[ 0 ];
   IPEndPoint^ localEndPoint = gcnew IPEndPoint( ipAddress,11000 );
   
   // Create a TCP/IP socket.
   Socket^ listener = gcnew Socket( AddressFamily::InterNetwork,SocketType::Stream,ProtocolType::Tcp );
   
   // Bind the socket to the local endpoint, and listen for incoming connections.
   listener->Bind( localEndPoint );
   listener->Listen( 100 );
   for ( ; ;  )
   {
      
      // Set the event to nonsignaled state.
      allDone->Reset();
      
      // Start an asynchronous socket to listen for connections and receive data from the client.
      Console::WriteLine( "Waiting for a connection..." );
      
      // Accept the connection and receive the first 10 bytes of data.
      int receivedDataSize = 10;
      listener->BeginAccept( receivedDataSize, gcnew AsyncCallback( AcceptReceiveCallback ), listener );
      
      // Wait until a connection is made and processed before continuing.
      allDone->WaitOne();

   }
}

static void AcceptReceiveCallback( IAsyncResult^ ar )
{
   // Get the socket that handles the client request.
   Socket^ listener = dynamic_cast<Socket^>(ar->AsyncState);

   // End the operation and display the received data on the console.
   array<Byte>^Buffer;
   int bytesTransferred;
   Socket^ handler = listener->EndAccept( Buffer, bytesTransferred, ar );
   String^ stringTransferred = Encoding::ASCII->GetString( Buffer, 0, bytesTransferred );
   Console::WriteLine( stringTransferred );
   Console::WriteLine( "Size of data transferred is {0}", bytesTransferred );

   // Create the state object for the asynchronous receive.
   StateObject^ state = gcnew StateObject;
   state->workSocket = handler;
   handler->BeginReceive( state->buffer, 0, StateObject::BufferSize, static_cast<SocketFlags>(0), gcnew AsyncCallback( ReadCallback ), state );
}


    // This server waits for a connection and then uses asynchronous operations to
    // accept the connection with initial data sent from the client.
         
    
    // Establish the local endpoint for the socket.

    IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
    IPAddress ipAddress = ipHostInfo.AddressList[0];
    IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
   
    // Create a TCP/IP socket.
    Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );

    // Bind the socket to the local endpoint, and listen for incoming connections.
    listener.Bind(localEndPoint);
    listener.Listen(100);

    while (true) 
    {
        // Set the event to nonsignaled state.
        allDone.Reset();

        // Start an asynchronous socket to listen for connections and receive data from the client.
        Console.WriteLine("Waiting for a connection...");

        // Accept the connection and receive the first 10 bytes of data.
        int receivedDataSize = 10;
        listener.BeginAccept(receivedDataSize, new AsyncCallback(AcceptReceiveCallback), listener);
         
        // Wait until a connection is made and processed before continuing.
        allDone.WaitOne();
    }

}


public static void AcceptReceiveCallback(IAsyncResult ar) 
{
    // Get the socket that handles the client request.
    Socket listener = (Socket) ar.AsyncState;
    
    // End the operation and display the received data on the console.
    byte[] Buffer;
    int bytesTransferred;
    Socket handler = listener.EndAccept(out Buffer, out bytesTransferred, ar);
    string stringTransferred = Encoding.ASCII.GetString(Buffer, 0, bytesTransferred);

    Console.WriteLine(stringTransferred);
    Console.WriteLine("Size of data transferred is {0}", bytesTransferred);
          
    // Create the state object for the asynchronous receive.
    StateObject state = new StateObject();
    state.workSocket = handler;
    handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,
    new AsyncCallback(ReadCallback), state);
}

注解

可以使用面向连接的协议BeginAccept方法以异步处理传入的连接尝试。Connection-oriented protocols can use the BeginAccept method to asynchronously process incoming connection attempts. 以异步方式接受连接,可发送和接收单独的执行线程中的数据。Accepting connections asynchronously enables you to send and receive data within a separate execution thread. 此重载允许您指定要接受初始传输中的字节数receiveSize参数。This overload allows you to specify the number of bytes to accept in the initial transfer in the receiveSize parameter.

然后再调用BeginAccept方法时,必须调用Listen方法来侦听并对传入连接请求进行排队。Before calling the BeginAccept method, you must call the Listen method to listen for and queue incoming connection requests.

必须创建实现一个回调方法AsyncCallback委托并将传递到其名称BeginAccept方法。You must create a callback method that implements the AsyncCallback delegate and pass its name to the BeginAccept method. 为此,请在最低限度下,必须通过侦听Socket对象传递给BeginAccept通过state参数。To do this, at the very minimum, you must pass the listening Socket object to BeginAccept through the state parameter. 如果回调需要详细信息,可以创建一个小类来保存Socket和其他所需的信息。If your callback needs more information, you can create a small class to hold the Socket and the other required information. 传递到此类的实例BeginAccept方法通过state参数。Pass an instance of this class to the BeginAccept method through the state parameter.

回调方法应该调用EndAccept方法。Your callback method should invoke the EndAccept method. 当应用程序调用BeginAccept,系统通常使用一个单独的线程来执行指定的回调方法,并阻止上EndAccept直到检索到挂起的连接。When your application calls BeginAccept, the system usually uses a separate thread to execute the specified callback method and blocks on EndAccept until a pending connection is retrieved.

EndAccept 返回一个新Socket可用于发送和接收数据与远程主机。EndAccept returns a new Socket that you can use to send and receive data with the remote host. 不能使用此返回Socket为接受任何其他连接的连接队列。You cannot use this returned Socket to accept any additional connections from the connection queue. 如果你想要阻止调用后的原始线程BeginAccept方法,请使用WaitHandle.WaitOneIf you want the original thread to block after you call the BeginAccept method, use WaitHandle.WaitOne. 在调用 Set 方法ManualResetEvent在回调方法时所需的原始线程继续执行。Call the Set method on a ManualResetEvent in the callback method when you want the original thread to continue executing.

系统还可能使用调用线程来调用该回调方法。The system may also use the calling thread to invoke the callback method. 在这种情况下,CompletedSynchronously对返回的属性IAsyncResult会将设置为指示BeginAccept方法以同步方式完成。In this case, the CompletedSynchronously property on the returned IAsyncResult will be set to indicate that the BeginAccept method completed synchronously.

编写回调方法的其他信息,请参阅委托作为回调方法进行封送For additional information on writing callback methods see Marshaling a Delegate as a Callback Method.

若要取消挂起调用BeginAccept方法,关闭SocketTo cancel a pending call to the BeginAccept method, close the Socket. Close回调的异步操作正在进行中时,调用方法,提供给BeginAccept调用方法。When the Close method is called while an asynchronous operation is in progress, the callback provided to the BeginAccept method is called. 随后调用EndAccept方法将引发ObjectDisposedException以指示已取消该操作。A subsequent call to the EndAccept method will throw an ObjectDisposedException to indicate that the operation has been cancelled.

备注

您可以调用使用RemoteEndPoint属性所返回的Socket对象来标识远程主机的网络地址和端口号。You can call use the RemoteEndPoint property of the returned Socket object to identify the remote host's network address and port number.

备注

如果你收到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.

另请参阅

BeginAccept(Socket, Int32, AsyncCallback, Object) BeginAccept(Socket, Int32, AsyncCallback, Object) BeginAccept(Socket, Int32, AsyncCallback, Object) BeginAccept(Socket, Int32, AsyncCallback, Object)

开始异步操作以接受从指定套接字传入的连接尝试并接收客户端应用程序发送的第一个数据块。Begins an asynchronous operation to accept an incoming connection attempt from a specified socket and receives the first block of data sent by the client application.

public:
 IAsyncResult ^ BeginAccept(System::Net::Sockets::Socket ^ acceptSocket, int receiveSize, AsyncCallback ^ callback, System::Object ^ state);
public IAsyncResult BeginAccept (System.Net.Sockets.Socket acceptSocket, int receiveSize, AsyncCallback callback, object state);
member this.BeginAccept : System.Net.Sockets.Socket * int * AsyncCallback * obj -> IAsyncResult
Public Function BeginAccept (acceptSocket As Socket, receiveSize As Integer, callback As AsyncCallback, state As Object) As IAsyncResult

参数

acceptSocket
Socket Socket Socket Socket

接受的 Socket 对象。The accepted Socket object. 此值可为 nullThis value may be null.

receiveSize
Int32 Int32 Int32 Int32

要接收的最大字节数。The maximum number of bytes to receive.

state
Object Object Object Object

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

返回

一个 IAsyncResult 对象,它引用异步 Socket 对象创建。An IAsyncResult object that references the asynchronous Socket object creation.

异常

此方法需要 Windows NT。Windows NT is required for this method.

正在接受的套接字不会侦听连接。The accepting socket is not listening for connections. 在调用 Bind(EndPoint) 之前必须调用 Listen(Int32)BeginAccept(AsyncCallback, Object)You must call Bind(EndPoint) and Listen(Int32) before calling BeginAccept(AsyncCallback, Object).

- 或 --or- 已接受的套接字是绑定的。The accepted socket is bound.

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

示例

下面的代码示例打开一个套接字并接受异步连接。The following code example opens a socket and accepts an asynchronous connection. 在此示例中,套接字接受前 10 个字节的数据并acceptSocket参数是null,这将强制BeginAccept方法来创建接受的套接字。In this example, the socket accepts the initial 10 bytes of data and the acceptSocket parameter is null, which forces the BeginAccept method to create the accepted socket. 接收的字节数和数据的回调委托显示在控制台上。The number of bytes received and the data are displayed on the console by the callback delegate. 请参阅BeginReceive如何接收剩余数据的说明。See BeginReceive for a description of how the remaining data is received.

   // This server waits for a connection and then uses asynchronous operations to
   // accept the connection with initial data sent from the client.
   // Establish the local endpoint for the socket.
   IPHostEntry^ ipHostInfo = Dns::GetHostEntry( Dns::GetHostName() );
   IPAddress^ ipAddress = ipHostInfo->AddressList[ 0 ];
   IPEndPoint^ localEndPoint = gcnew IPEndPoint( ipAddress,11000 );

   // Create a TCP/IP socket.
   Socket^ listener = gcnew Socket( AddressFamily::InterNetwork,SocketType::Stream,ProtocolType::Tcp );

   // Bind the socket to the local endpoint, and listen for incoming connections.
   listener->Bind( localEndPoint );
   listener->Listen( 100 );
   for ( ; ;  )
   {
      // Set the event to nonsignaled state.
      allDone->Reset();

      // Start an asynchronous socket to listen for connections and receive data from the client.
      Console::WriteLine( "Waiting for a connection..." );

      // Accept the connection and receive the first 10 bytes of data. 
      // BeginAccept() creates the accepted socket.
      int receivedDataSize = 10;
      listener->BeginAccept( nullptr, receivedDataSize, gcnew AsyncCallback( AcceptReceiveDataCallback ), listener );

      // Wait until a connection is made and processed before continuing.
      allDone->WaitOne();
   }
}

static void AcceptReceiveDataCallback( IAsyncResult^ ar )
{
   // Get the socket that handles the client request.
   Socket^ listener = dynamic_cast<Socket^>(ar->AsyncState);
   
   // End the operation and display the received data on the console.
   array<Byte>^Buffer;
   int bytesTransferred;
   Socket^ handler = listener->EndAccept( Buffer, bytesTransferred, ar );
   String^ stringTransferred = Encoding::ASCII->GetString( Buffer, 0, bytesTransferred );
   Console::WriteLine( stringTransferred );
   Console::WriteLine( "Size of data transferred is {0}", bytesTransferred );
   
   // Create the state object for the asynchronous receive.
   StateObject^ state = gcnew StateObject;
   state->workSocket = handler;
   handler->BeginReceive( state->buffer, 0, StateObject::BufferSize, static_cast<SocketFlags>(0), gcnew AsyncCallback( ReadCallback ), state );
}

    // This server waits for a connection and then uses asynchronous operations to
    // accept the connection with initial data sent from the client.
               
    // Establish the local endpoint for the socket.

    IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
    IPAddress ipAddress = ipHostInfo.AddressList[0];
    IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);

    // Create a TCP/IP socket.
    Socket listener = new Socket(AddressFamily.InterNetwork,
        SocketType.Stream, ProtocolType.Tcp );

    // Bind the socket to the local endpoint, and listen for incoming connections.
    listener.Bind(localEndPoint);
    listener.Listen(100);

    while (true) 
    {
        // Set the event to nonsignaled state.
        allDone.Reset();

        // Start an asynchronous socket to listen for connections and receive data from the client.
        Console.WriteLine("Waiting for a connection...");

        // Accept the connection and receive the first 10 bytes of data. 
        // BeginAccept() creates the accepted socket.
        int receivedDataSize = 10;
        listener.BeginAccept(null, receivedDataSize, new AsyncCallback(AcceptReceiveDataCallback), listener);

        // Wait until a connection is made and processed before continuing.
        allDone.WaitOne();
    }
}



public static void AcceptReceiveDataCallback(IAsyncResult ar) 
{
    // Get the socket that handles the client request.
    Socket listener = (Socket) ar.AsyncState;
    
    // End the operation and display the received data on the console.
    byte[] Buffer;
    int bytesTransferred;
    Socket handler = listener.EndAccept(out Buffer, out bytesTransferred, ar);
    string stringTransferred = Encoding.ASCII.GetString(Buffer, 0, bytesTransferred);

    Console.WriteLine(stringTransferred);
    Console.WriteLine("Size of data transferred is {0}", bytesTransferred);

    // Create the state object for the asynchronous receive.
    StateObject state = new StateObject();
    state.workSocket = handler;
    handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,
    new AsyncCallback(ReadCallback), state);
}

注解

可以使用面向连接的协议BeginAccept方法以异步处理传入的连接尝试。Connection-oriented protocols can use the BeginAccept method to asynchronously process incoming connection attempts. 以异步方式接受连接使你能够发送和接收单独的执行线程中的数据。Accepting connections asynchronously gives you the ability to send and receive data within a separate execution thread. 此重载允许您指定在接受的套接字acceptSocket参数。This overload allows you to specify the accepted socket in the acceptSocket parameter. 如果此参数为null,通过创建接受的套接字BeginAccept方法。If this parameter is null, the accepted socket is created by the BeginAccept method. 可以指定要接受初始传输中的字节数receiveSize参数。You can specify the number of bytes to accept in the initial transfer in the receiveSize parameter.

然后再调用BeginAccept方法时,必须调用Listen方法来侦听并对传入连接请求进行排队。Before calling the BeginAccept method, you must call the Listen method to listen for and queue incoming connection requests.

必须创建实现一个回调方法AsyncCallback委托并将传递到其名称BeginAccept方法。You must create a callback method that implements the AsyncCallback delegate and pass its name to the BeginAccept method. 为此,请在最低限度下,必须通过侦听Socket对象传递给BeginAccept通过state参数。To do this, at the very minimum, you must pass the listening Socket object to BeginAccept through the state parameter. 如果回调需要详细信息,可以创建一个小类来保存Socket和其他所需的信息。If your callback needs more information, you can create a small class to hold the Socket and the other required information. 传递到此类的实例BeginAccept方法通过state参数。Pass an instance of this class to the BeginAccept method through the state parameter.

回调方法应该调用EndAccept方法。Your callback method should invoke the EndAccept method. 当应用程序调用BeginAccept,系统通常使用一个单独的线程来执行指定的回调方法,并阻止上EndAccept直到检索到挂起的连接。When your application calls BeginAccept, the system usually uses a separate thread to execute the specified callback method and blocks on EndAccept until a pending connection is retrieved.

EndAccept 返回一个新Socket对象可用于发送和接收数据与远程主机。EndAccept returns a new Socket object that you can use to send and receive data with the remote host. 不能使用此返回Socket为接受任何其他连接的连接队列。You cannot use this returned Socket to accept any additional connections from the connection queue. 如果你想要阻止调用后的原始线程BeginAccept方法,请使用WaitHandle.WaitOneIf you want the original thread to block after you call the BeginAccept method, use WaitHandle.WaitOne. 在调用 Set 方法ManualResetEvent在回调方法时所需的原始线程继续执行。Call the Set method on a ManualResetEvent in the callback method when you want the original thread to continue executing.

系统还可能使用调用线程来调用该回调方法。The system may also use the calling thread to invoke the callback method. 在这种情况下,CompletedSynchronously对返回的属性IAsyncResult会将设置为指示BeginAccept方法以同步方式完成。In this case, the CompletedSynchronously property on the returned IAsyncResult will be set to indicate that the BeginAccept method completed synchronously.

有关编写回调方法的其他信息,请参阅委托作为回调方法进行封送For additional information on writing callback methods, see Marshaling a Delegate as a Callback Method.

若要取消挂起调用BeginAccept方法,关闭SocketTo cancel a pending call to the BeginAccept method, close the Socket. Close回调的异步操作正在进行中时,调用方法,提供给BeginAccept调用方法。When the Close method is called while an asynchronous operation is in progress, the callback provided to the BeginAccept method is called. 随后调用EndAccept方法将引发ObjectDisposedException以指示已取消该操作。A subsequent call to the EndAccept method will throw an ObjectDisposedException to indicate that the operation has been cancelled.

备注

可以使用RemoteEndPoint属性所返回的Socket对象来标识远程主机的网络地址和端口号。You can use the RemoteEndPoint property of the returned Socket object to identify the remote host's network address and port number.

备注

如果你收到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.

另请参阅

适用于