NegotiateStream.EndRead(IAsyncResult) 方法
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
结束通过调用 BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) 而启动的异步读操作。
public:
override int EndRead(IAsyncResult ^ asyncResult);
public override int EndRead (IAsyncResult asyncResult);
override this.EndRead : IAsyncResult -> int
Public Overrides Function EndRead (asyncResult As IAsyncResult) As Integer
参数
- asyncResult
- IAsyncResult
调用 BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) 后返回的 IAsyncResult 实例。
返回
Int32 值,该值指定从基础流中读取的字节数。
例外
asyncResult
为 null
。
asyncResult 并不是通过调用 BeginRead(Byte[], Int32, Int32, AsyncCallback, Object) 而创建的。
读操作失败。
示例
下面的代码示例演示如何结束异步读取操作。 有关演示如何启动操作的示例,请参阅 BeginRead。
static void EndReadCallback( IAsyncResult^ ar )
{
// Get the saved data.
ClientState^ cState = dynamic_cast<ClientState^>(ar->AsyncState);
TcpClient^ clientRequest = cState->Client;
NegotiateStream^ authStream = dynamic_cast<NegotiateStream^>(cState->AuthStream);
// Get the buffer that stores the message sent by the client.
int bytes = -1;
// Read the client message.
try
{
bytes = authStream->EndRead( ar );
cState->Message->Append( Encoding::UTF8->GetChars( cState->Buffer, 0, bytes ) );
if ( bytes != 0 )
{
authStream->BeginRead( cState->Buffer, 0, cState->Buffer->Length, gcnew AsyncCallback( EndReadCallback ), cState );
return;
}
}
catch ( Exception^ e )
{
// A real application should do something
// useful here, such as logging the failure.
Console::WriteLine( L"Client message exception:" );
Console::WriteLine( e );
cState->Waiter->Set();
return;
}
IIdentity^ id = authStream->RemoteIdentity;
Console::WriteLine( L"{0} says {1}", id->Name, cState->Message );
cState->Waiter->Set();
}
private static void EndReadCallback(ClientState cState, int bytes)
{
NegotiateStream authStream = (NegotiateStream)cState.AuthenticatedStream;
// Read the client message.
try
{
cState.Message.Append(Encoding.UTF8.GetChars(cState.Buffer, 0, bytes));
if (bytes != 0)
{
Task<int> readTask = authStream.ReadAsync(cState.Buffer, 0, cState.Buffer.Length);
readTask
.ContinueWith(task => { EndReadCallback(cState, task.Result); })
.Wait();
return;
}
}
catch (Exception e)
{
// A real application should do something
// useful here, such as logging the failure.
Console.WriteLine("Client message exception:");
Console.WriteLine(e);
return;
}
IIdentity id = authStream.RemoteIdentity;
Console.WriteLine("{0} says {1}", id.Name, cState.Message.ToString());
}
注解
如果操作尚未完成,此方法将一直阻止,直到它完成。
若要同步执行此操作,请使用 Read 方法。
在成功进行身份验证之前,无法调用此方法。 若要进行身份验证,请调用 、、AuthenticateAsClientAsync、AuthenticateAsServerAsyncBeginAuthenticateAsClientAuthenticateAsServer、 或 BeginAuthenticateAsServer 方法之一。AuthenticateAsClient