private void OnAccept(Task<TcpClient> result)
{
TcpClient client = null;
// Accept current connection
try
{
client = result.Result;
}
catch
{
}
// If we have a connection, then process it
if (client != null)
{
OnClientAccepted(client);
ClientState state;
// Start authentication for SSL?
if (_useSsl)
{
state = new ClientState(client, _sslEncryptionPolicy);
_log.WriteLine("Server: starting SSL authentication.");
SslStream sslStream = null;
X509Certificate2 certificate = Configuration.Certificates.GetServerCertificate();
try
{
sslStream = (SslStream)state.Stream;
_log.WriteLine("Server: attempting to open SslStream.");
sslStream.AuthenticateAsServerAsync(certificate, false, _sslProtocols, false).ContinueWith(t =>
{
certificate.Dispose();
OnAuthenticate(t, state);
}, TaskScheduler.Default);
}
catch (Exception ex)
{
_log.WriteLine("Server: Exception: {0}", ex);
certificate.Dispose();
state.Dispose(); // close connection to client
}
}
else
{
state = new ClientState(client);
// Start listening for data from the client connection
try
{
state.Stream.BeginRead(state.ReceiveBuffer, 0, state.ReceiveBuffer.Length, OnReceive, state);
}
catch
{
}
}
}
// Listen for more client connections
try
{
_listener.AcceptTcpClientAsync().ContinueWith(t => OnAccept(t), TaskScheduler.Default);
}
catch
{
}
}