为什么SSL Stream使用2048的字节数组?
Why does SSL Stream use a byte array of 2048?
读取TCP SSL example from MSDN后,他们使用一个字节数组将数据读入流中。数组限制为 2048 是否有原因?如果 TCP 发送一个比 2048 更长的数组怎么办?此外,buffer.Length 属性 如何在流发生变化时继续读取流。这对我来说完全没有意义。为什么要读取缓冲区的长度,难道你不想读取进入流的增量字节的长度吗?
static string ReadMessage(SslStream sslStream)
{
// Read the message sent by the client.
// The client signals the end of the message using the
// "<EOF>" marker.
byte [] buffer = new byte[2048];
StringBuilder messageData = new StringBuilder();
int bytes = -1;
do
{
// Read the client's test message.
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 or an empty message.
if (messageData.ToString().IndexOf("<EOF>") != -1)
{
break;
}
} while (bytes !=0);
return messageData.ToString();
}
当从任何类型的流(不仅仅是 SslStream
)中读取时,仅仅因为您请求 X 字节,它们就可以返回 1 到 X 字节之间的任何位置。这就是 Read
返回的 bytes
的用途,看看你读了多少。
如果你给 Read
一个巨大的缓冲区,它只会填充前几个 1000 左右字节,给它一个更大的缓冲区是对 space 的浪费。如果您需要的数据比缓冲区大,您可以多次请求数据。
处理网络流时要记住的一件重要事情是,在发送方写入一次并不意味着在接收方读取一次。写入可以组合在一起或在任意点分开,这就是为什么要有某种形式的 Message Framing 才能知道什么时候有 "all the data"。在您发布的示例中,他们使用标记 <EOF>
来表示 "end of message".
读取TCP SSL example from MSDN后,他们使用一个字节数组将数据读入流中。数组限制为 2048 是否有原因?如果 TCP 发送一个比 2048 更长的数组怎么办?此外,buffer.Length 属性 如何在流发生变化时继续读取流。这对我来说完全没有意义。为什么要读取缓冲区的长度,难道你不想读取进入流的增量字节的长度吗?
static string ReadMessage(SslStream sslStream)
{
// Read the message sent by the client.
// The client signals the end of the message using the
// "<EOF>" marker.
byte [] buffer = new byte[2048];
StringBuilder messageData = new StringBuilder();
int bytes = -1;
do
{
// Read the client's test message.
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 or an empty message.
if (messageData.ToString().IndexOf("<EOF>") != -1)
{
break;
}
} while (bytes !=0);
return messageData.ToString();
}
当从任何类型的流(不仅仅是 SslStream
)中读取时,仅仅因为您请求 X 字节,它们就可以返回 1 到 X 字节之间的任何位置。这就是 Read
返回的 bytes
的用途,看看你读了多少。
如果你给 Read
一个巨大的缓冲区,它只会填充前几个 1000 左右字节,给它一个更大的缓冲区是对 space 的浪费。如果您需要的数据比缓冲区大,您可以多次请求数据。
处理网络流时要记住的一件重要事情是,在发送方写入一次并不意味着在接收方读取一次。写入可以组合在一起或在任意点分开,这就是为什么要有某种形式的 Message Framing 才能知道什么时候有 "all the data"。在您发布的示例中,他们使用标记 <EOF>
来表示 "end of message".