C# 连续读取 SslStream(长连接,持续数天)并且高效无无限循环
C# Read from SslStream continuously (long connection, last for up to days) and Efficiently without infinite loop
我完全不熟悉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 连续读取,但他们使用无限循环来做到这一点,在服务器端,可能有成千上万的客户端连接到它,所以可能的性能不佳让我担心,像这个 :
所以我想知道是否有更好的方法可以从持久的 SslStream 连接中持续读取。
我知道使用裸套接字我可以使用 SocketAsyncEventArgs 来知道何时有新数据准备就绪,我希望我可以用 SslStream 做到这一点,可能我误解了什么,任何想法都会不胜感激,提前致谢。
这是我的尝试。我没有永远循环,而是选择了递归。此方法将 return 立即 但会在 EOF
被击中时触发一个事件并继续阅读:
public static void ReadFromSSLStreamAsync(
SslStream sslStream,
Action<string> result,
Action<Exception> error,
StringBuilder stringBuilder = null)
{
const string EOFToken = "<EOF>";
stringBuilder = stringBuilder ?? new StringBuilder();
var buffer = new byte[4096];
try
{
sslStream.BeginRead(buffer, 0, buffer.Length, asyncResult =>
{
// Read all bytes avaliable from stream and then
// add them to string builder
{
int bytesRead;
try
{
bytesRead = sslStream.EndRead(asyncResult);
}
catch (Exception ex)
{
error?.Invoke(ex);
return;
}
// Use Decoder class to convert from bytes to
// UTF8 in case a character spans two buffers.
var decoder = Encoding.UTF8.GetDecoder();
var buf = new char[decoder.GetCharCount(buffer, 0, bytesRead)];
decoder.GetChars(buffer, 0, bytesRead, buf, 0);
stringBuilder.Append(buf);
}
// Find the EOFToken, if found copy all data before the token
// and send it to event, then remove it from string builder
{
int tokenIndex;
while((tokenIndex = stringBuilder.ToString().IndexOf(EOFToken)) != -1)
{
var buf = new char[tokenIndex];
stringBuilder.CopyTo(0, buf, 0, tokenIndex);
result?.Invoke(new string(buf));
stringBuilder.Remove(0, tokenIndex + EOFToken.Length);
}
}
// Continue reading...
ReadFromSSLStreamAsync(sslStream, result, error, stringBuilder);
}, null);
}
catch(Exception ex)
{
error?.Invoke(ex);
}
}
你可以这样称呼它:
ReadFromSSLStreamAsync(sslStream, sslData =>
{
Console.WriteLine($"Finished: {sslData}");
}, error =>
{
Console.WriteLine($"Errored: {error}");
});
它不是 TaskAsync
,因此您不必 await
。但它是异步的,所以你的线程可以继续做其他事情。
我完全不熟悉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 连续读取,但他们使用无限循环来做到这一点,在服务器端,可能有成千上万的客户端连接到它,所以可能的性能不佳让我担心,像这个 :
所以我想知道是否有更好的方法可以从持久的 SslStream 连接中持续读取。
我知道使用裸套接字我可以使用 SocketAsyncEventArgs 来知道何时有新数据准备就绪,我希望我可以用 SslStream 做到这一点,可能我误解了什么,任何想法都会不胜感激,提前致谢。
这是我的尝试。我没有永远循环,而是选择了递归。此方法将 return 立即 但会在 EOF
被击中时触发一个事件并继续阅读:
public static void ReadFromSSLStreamAsync(
SslStream sslStream,
Action<string> result,
Action<Exception> error,
StringBuilder stringBuilder = null)
{
const string EOFToken = "<EOF>";
stringBuilder = stringBuilder ?? new StringBuilder();
var buffer = new byte[4096];
try
{
sslStream.BeginRead(buffer, 0, buffer.Length, asyncResult =>
{
// Read all bytes avaliable from stream and then
// add them to string builder
{
int bytesRead;
try
{
bytesRead = sslStream.EndRead(asyncResult);
}
catch (Exception ex)
{
error?.Invoke(ex);
return;
}
// Use Decoder class to convert from bytes to
// UTF8 in case a character spans two buffers.
var decoder = Encoding.UTF8.GetDecoder();
var buf = new char[decoder.GetCharCount(buffer, 0, bytesRead)];
decoder.GetChars(buffer, 0, bytesRead, buf, 0);
stringBuilder.Append(buf);
}
// Find the EOFToken, if found copy all data before the token
// and send it to event, then remove it from string builder
{
int tokenIndex;
while((tokenIndex = stringBuilder.ToString().IndexOf(EOFToken)) != -1)
{
var buf = new char[tokenIndex];
stringBuilder.CopyTo(0, buf, 0, tokenIndex);
result?.Invoke(new string(buf));
stringBuilder.Remove(0, tokenIndex + EOFToken.Length);
}
}
// Continue reading...
ReadFromSSLStreamAsync(sslStream, result, error, stringBuilder);
}, null);
}
catch(Exception ex)
{
error?.Invoke(ex);
}
}
你可以这样称呼它:
ReadFromSSLStreamAsync(sslStream, sslData =>
{
Console.WriteLine($"Finished: {sslData}");
}, error =>
{
Console.WriteLine($"Errored: {error}");
});
它不是 TaskAsync
,因此您不必 await
。但它是异步的,所以你的线程可以继续做其他事情。