// guarantees to close the socket on error
public static void TlsConnect(Socket sock, string host, RemoteCertificateValidationCallback rcvc, Action<Exception,SslStream> cb)
{
SslStream ssl = null;
try {
ssl = new SslStream (new NetworkStream (sock, true), false, rcvc);
ssl.BeginAuthenticateAsClient (host, (ar) => {
try {
ssl.EndAuthenticateAsClient (ar);
} catch (Exception ex) {
ssl.Dispose ();
sock.Dispose ();
cb (ex, null);
return;
}
cb (null, ssl);
}, null);
} catch (Exception ex) {
if (ssl != null)
ssl.Dispose ();
sock.Dispose ();
cb (ex, null);
}
}