我正在开发一个 .NET 服务,它试图建立与服务器的安全连接。该服务事先不知道服务器是否支持安全连接。这就是为什么我只是尝试建立安全连接,如果失败,我将退回到不安全的连接。
tcpClient.BeginConnect(hostname, port, Start, null);
private void Start(IAsyncResult asyncResult)
{
X509CertificateCollection certCollection = new X509CertificateCollection();
certCollection.Add(new X509Certificate2("cert.p12", "pw"));
SslStream sslStream = new SslStream(tcpClient.GetStream(), false, new RemoteCertificateValidationCallback(ValidateCertificate));
sslStream.ReadTimeout = 2000;
sslStream.BeginAuthenticateAsClient("name", certCollection, SslProtocols.Tls, false, AuthenticateCallback, sslStream);
}
private void AuthenticateCallback(IAsyncResult asyncResult)
{
stream.ReadTimeout = -1;
// secure connection has been established
}
如果服务器不支持请求的加密,则在调用回调方法之前需要 2 分钟。使用同步方法AuthenticateAsClient()
只需要预期的 2 秒(根据设置的请求ReadTimeout
):
sslStream.AuthenticateAsClient("ESLD Server", certCollection, SslProtocols.Tls, false);
为什么超时只适用于同步方法?如何减少异步方法的回调时间?或者有没有更好的方法来检查服务器是否支持安全连接?