【发布时间】:2020-12-11 13:00:28
【问题描述】:
我对C#完全陌生,需要对客户端和服务器之间发送和接收的数据进行加密,在google了两天后,学会了最好的方法是使用SslStream,我找到的一些答案给出了很好的例子,但它们都是以某种方式假设我们只需要阅读一条消息然后关闭连接,这完全不是我的情况,每当用户触发他的设备通过持久连接发送消息时我都必须阅读。 Microsoft 文档中的一个示例:
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. <------ In my case,I don't have EOF
if (messageData.ToString().IndexOf("<EOF>") != -1)
{
break;
}
} while (bytes !=0);
return messageData.ToString();
}
和其他答案实际上告诉我如何从 SslStream 连续读取,但他们使用无限循环来做到这一点,在服务器端,可能有数千个客户端连接到它,所以可能的性能不佳让我担心,比如这个 : Read SslStream continuously in C# Web MVC 5 project
所以我想知道是否有更好的方法从持久的 SslStream 连接中持续读取。
我知道使用裸套接字我可以使用 SocketAsyncEventArgs 来知道何时准备好新数据,我希望我可以使用 SslStream 来做到这一点,可能我误解了一些东西,任何想法都将不胜感激,谢谢前进。
【问题讨论】:
-
SSLStream 的工作原理docs.microsoft.com/en-us/dotnet/api/…
-
简单的答案是保持无限循环,但使用
await ReadAsync(...。当方法暂停并等待 I/O 时,不会执行任何线程。 -
@JeremyLakeman 这是正确的答案。我在搜索答案时确实看到了
ReadAsync,但我误解了当缓冲区中没有数据时它会立即返回零。它实际上只在连接关闭时返回零。非常感谢!