How to Quit() Unity application when using sockets?

Topic

How to “properly” terminate a client-server connection to prevent Unity freezing when Application.Quit() is called. I’m learning about sockets. This situation is new to me.

Problem description

For a long time I’ve had the issue of builds freezing upon exiting. I believe that a socket is not properly closed and preventing Unity from exiting correctly. I’ve come to this conclusion by elimination.

Situation

A method like the one below is used. This produce a freeze.

    public void Logoff()
    {
        try
        {
            if (serverSocket!= null)
            {
                if (serverSocket.Connected)
                {
                    serverSocket.Shutdown(SocketShutdown.Both);
                    serverSocket.Close();
                }
            }
        }
        catch (Exception e)
        {
            print(e.ToString());
        }
        Application.Quit();
    }

Same code, but with an IEnumerator waiting for disconnection. However, the socket remains connected and Application.Quit() is never called.

    public void Logoff()
    {
        try
        {
            if (serverSocket!= null)
            {
                if (serverSocket.Connected)
                {
                    serverSocket.Shutdown(SocketShutdown.Both);
                    serverSocket.Close();
                }
            }
        }
        catch (Exception e)
        {
            print(e.ToString());
        }
        StartCoroutine("Exiter");
    }

    IEnumerator Exiter()
    {
        while (serverSocket.Connected)
        {
            yield return null;
        }
        Application.Quit();
    }

Additional info

Server recognize a disconnect when closing the application from the task manager or when stopping ‘play mode’ in the Unity editor. I cannot produce a ‘true’ disconnect from code.
Async client and server, AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp.

Same question. I’m using a packet dropper and debugging my app when it hangs and it’s hitting Application.Quit. Call stack shows ntdll.dll!NtWaitForSingleObject and a bunch of stuff mentioning socket. Task manager says it’s waiting on network I/O