This looks problematic:
while (true)
{
var plainSocket = await listener.AcceptAsync();
var socket = new TlsServerSocket(plainSocket);
socket.Parameters.Certificate = CertificateChain.BuildFrom(certificate);
await socket.NegotiateAsync();
Task.Run(() => HandleClientAsync(socket));
}
The first problem is that the three lines below AcceptAsync
can throw an exception, which would make the StartServer
method to fail. For example, NegotiateAsync
will fail when an outdated TLS client attempts to connect, or if the client does not accept the certificate.
Another problem is that await socket.NegotiateAsync()
can take a lot of time to finish in some scenarios. During this time, new connections won't be accepted. For example, if the client is a slow device, or if it asks the user whether to accept the server's certificate, this could make NegotiateAsync
take several minutes.
Consider calling HandleClientAsync
as soon as a connection is accepted to prevent this. For example:
while (true)
{
var plainSocket = await listener.AcceptAsync();
Task.Run(() => HandleClientAsync(plainSocket));
}
And make sure to handle errors from NegotiateAsync
(writing them into the log might be useful).