0

The releated code

            while(true)
            {
                List<Socket> accept=new List<Socket>{ClientListener.Server,RequestListener.Server};
                Socket.Select(accept,null,null,-1);
                foreach(var i in accept)
                {
                    if(i == ClientListener.Server)
                    {
                        Task.Run(()=>Authenticate(ClientListener.AcceptTcpClient()));
                    }
                    else
                    ....
                }
           }
        private void Authenticate(TcpClient client)
        {
            SslStream ssl=new SslStream(client.GetStream(),false);
            try
            {
                ssl.AuthenticateAsServer(serverCertificate,false,SslProtocols.Tls,true);
                ssl.ReadTimeout = 1000;
                ssl.WriteTimeout = 1000;
            }catch(Exception e)
            {
                ssl.Close();
                client.Close();
                ssl.Dispose();
                client.Dispose();
                return;
            }
       }

The code is very basical code,but it has a very wired bug.

Firstly,At the beginning that the server started,everything worked.

After almost one hour,the SslStream.AuthenticateAsServer() throw error: Received an unexpected EOF or 0 bytes from the transport stream

And then,about three times connect the server,the client that is SslStream.AuthenticateAsClent throw error:Received an unexpected EOF or 0 bytes from the transport stream.(Note. before it, the client authenticate is ok)

another strange thing maybe releate it when I first connect the server,the memory will increase but during it,I don't connect it again.

1 Answers1

0

You are probably exhausting the system resources, either the sockets and/or the threads:

while (true)
{
   Task.Run(); // Bogus
}

Add the using keyword

using SslStream ssl =new SslStream(client.GetStream(), false);

This will release the SslStream when there is no exception.

Set the timeout before calling AuthenticateAsServer.

Do not mix async & sync code flow: await the task you are creating, or better, use AuthenticateAsServerAsync and await the resulting Task.

ycrumeyrolle
  • 495
  • 4
  • 15
  • yeah,I have observed many threads running,But why it not release self,when the function is end? – mohuazheliu Aug 06 '21 at 09:41
  • I need pass sslstream to another thread,So it not should be release – mohuazheliu Aug 06 '21 at 09:53
  • Task.Run() start a new Task, eventualy a new Thread internaly. Without awaiting the Task, you are in mode Fire-and-Forget. Within a loop it will probably always crash. – ycrumeyrolle Aug 06 '21 at 10:04
  • The SslStream must be release. Maybe not within the method `Authenticate` that does not show that the SslStream is used somewhere else. – ycrumeyrolle Aug 06 '21 at 10:06