Nju Nju - 14 hours ago 2
C# Question

SSLSocket in .NET Core

I have code:

public void Connection()
{
TcpListener server = new TcpListener(IPAddress.Any, 5030);
server.Start();

while (true)
{
System.Console.WriteLine("Waiting for client");
TcpClient client = server.AcceptTcpClientAsync();
ProcessClient(TcpClient client);
}
}


Can someone explain me why I cannot use AcceptTcpClient? Only this Async version? And how should I use this function? I am using this example
https://msdn.microsoft.com/en-us//library/system.net.security.sslstream(v=vs.110).aspx

Answer

.net Core is all based on the asynchronous philosophy to achieve the maximum performance, hence a lot of synchronous methods have been removed because they're unnecessary.

To use the new async code you must use the await keyword to "stop" your code until the asynchornous function has been executed, and flag your function as async to be able to use the await keyword.

public async Task Connection()
{
    TcpListener server = new TcpListener(IPAddress.Any, 5030);
    server.Start();

    while (true)
    {
        System.Console.WriteLine("Waiting for client");
        TcpClient client = await server.AcceptTcpClientAsync();
        ProcessClient(TcpClient client);              
    }
}

BUT, beware, by what you're asking you never have used async, so don't jump to code until you read what is and how works async on .net or you will live a nightmare as a lot of things will not work as you expect. And as I said, if you target .net Core, async is not optional.