SslStream.Read(Byte[], Int32, Int32) 方法

定义

从此流中读取数据并将其存储在指定的数组中。

public:
 override int Read(cli::array <System::Byte> ^ buffer, int offset, int count);
public override int Read(byte[] buffer, int offset, int count);
override this.Read : byte[] * int * int -> int
Public Overrides Function Read (buffer As Byte(), offset As Integer, count As Integer) As Integer

参数

buffer
Byte[]

接收 Byte 从此流中读取的字节的数组。

offset
Int32

一个 Int32 ,其中包含从零开始存储从此流中读取的数据的位置 buffer

count
Int32

一个 Int32 包含要从此流中读取的最大字节数。

返回

一个 Int32 值,该值指定读取的字节数。 如果没有更多要读取的数据,则返回 0。

例外

buffernull

offset 小于零。

-或-

offset 大于长度 buffer

-或-

offset + count 大于长度 buffer

读取操作失败。 检查内部异常(如果存在)以确定失败的原因。

正在进行读取操作。

此对象已关闭。

身份验证未发生。

示例

下面的代码示例演示如何从 .SslStream

static string ReadMessage(SslStream sslStream)
{
    // Read the  message sent by the server.
    // The end of the message is signaled using the
    // "<EOF>" marker.
    byte [] buffer = new byte[2048];
    StringBuilder messageData = new StringBuilder();
    int bytes = -1;
    do
    {
        bytes = sslStream.Read(buffer, 0, buffer.Length);

        // Use Decoder class to convert from bytes to UTF8
        // in case a character spans two buffers.
        Decoder decoder = Encoding.UTF8.GetDecoder();
        char[] chars = new char[decoder.GetCharCount(buffer,0,bytes)];
        decoder.GetChars(buffer, 0, bytes, chars,0);
        messageData.Append (chars);
        // Check for EOF.
        if (messageData.ToString().IndexOf("<EOF>") != -1)
        {
            break;
        }
    } while (bytes != 0);

    return messageData.ToString();
}
Private Shared Function ReadMessage(sslStream As SslStream) As String

    ' Read the  message sent by the server.
    ' The end of the message is signaled using the "<EOF>" marker.
    Dim buffer = New Byte(2048) {}
    Dim messageData = New StringBuilder()
    Dim bytes As Integer

    Do
        bytes = sslStream.Read(buffer, 0, buffer.Length)

        ' Use Decoder class to convert from bytes to UTF8
        ' in case a character spans two buffers.        
        Dim decoder As Decoder = Encoding.UTF8.GetDecoder()
        Dim chars = New Char(decoder.GetCharCount(buffer, 0, bytes) - 1) {}
        decoder.GetChars(buffer, 0, bytes, chars, 0)
        messageData.Append(chars)

        ' Check for EOF.
        If messageData.ToString().IndexOf("<EOF>") <> -1 Then Exit Do
        
    Loop While bytes <> 0

    Return messageData.ToString()

End Function

注解

该方法从流中读取最大字节数 count ,并将其存储在 buffer 开头 offset。 不能执行多个同时读取操作。

在成功进行身份验证之前,无法调用此方法。 若要进行身份验证,请调用其中一种AuthenticateAsClientBeginAuthenticateAsClient方法 BeginAuthenticateAsServerAuthenticateAsServer

若要异步执行此操作,请使用 BeginRead 该方法。

适用于