Xamarin.Android System.Net.Sockets.TcpClient connection not closed when stopping app

Marcel Lorenz 81 Reputation points
2021-01-18T08:22:52.607+00:00

When I leave my application I close the established TCP connection to my windows app:

protected override void OnStop() {
    ConnectionManager.CloseConnection();
    base.OnStop();
}

Actually, I want to do it in OnDestroy but for now, I do it OnStop because I could not debug OnDestroy because the debugger disconnects.

ConnectionManager.CloseConnection() calls my custom tcp client ConnectionManager.tcpClient.Stop(); which executes the following codes:

/// <summary>
/// Closes the current connection.
/// </summary>
public void Stop() {
    lock (this.clientLock) {
        try { this.client.GetStream().Close(); } catch (ObjectDisposedException) { } catch (InvalidOperationException) { } catch (IOException) { }
        try { this.client.Close(); } catch (ObjectDisposedException) { } catch (InvalidOperationException) { } catch (IOException) { }
        this.client = new System.Net.Sockets.TcpClient();
    }

    this.OnConnectionClosed?.Invoke(this, EventArgs.Empty);
}

But the methods are executed correctly, but the connection is not closed.

There is no exception server-side thrown in GetStream().EndRead(...). Neither a caught exception (ObjectDisposedException, IOException, InvalidOperationException) nor a unhandled exception.

Also, the connection monitor of my custom TCP server still says that the client is connected. !client.IsConnected() is never true:

I'm not able to post the code of the ConnectionMonitoring, because every time I try to post the question containing the monitoring code. the forum crashes. But it's just a task checking each client every second using the following method:

public static class TcpClientExtensions {
    public static bool IsConnected(this System.Net.Sockets.TcpClient client) {
        if (client.Client == null)
            return false;

        if (!client.Connected)
            return false;

        if (!(client.Client.Poll(0, System.Net.Sockets.SelectMode.SelectWrite) && !client.Client.Poll(0, System.Net.Sockets.SelectMode.SelectError)))
            return false;

        return true;
    }
}
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,356 questions
{count} votes