Search code examples
androidnetwork-programmingxamarin.formstcp.net-standard-2.0

TcpClient.ConnectAsync and TcpClient.BeginConnect always returning true in Xamarin.Forms Android Application


I have made an application in my Xamarin.Forms project where I can connect my Android phone to my Computer using a TCP connection. I have found while using both TcpClient.ConnectAsync and TcpClient.BeginConnect, they both return that client.Connected is true even though the port isn't open. I have verified this because I tried random IPs and random ports and it still says connection was successful.

When using TcpClient.ConnectAsync, it doesn't return true unless I press the button that runs the code under Button_Clicked 2 times, but when using TcpClient.BeginConnect, client.Connected always returns true. I know for a fact that the client isn't connected because I have a detection system that kicks the user to the reconnect page when the connection is lost.

The code I have for my TCPClient in MainPage.xaml.cs:

TcpClient client = new TcpClient();
private async void Button_Clicked(object sender, EventArgs e)
{
    await client.ConnectAsync(ipAddress.Text, Convert.ToInt32(Port.Text));

    if (client.Connected)
    {
        await DisplayAlert("Connected", "The client has successfully connected", "OK");
    }
    else
    {
        await DisplayAlert("Connection Unsuccessful", "The client couldn't connect!", "OK");
    }
}

I have also tried using TcpClient.BeginConnect from How to set the timeout for a TcpClient?:

TcpClient client = new TcpClient();
private async void Button_Clicked(object sender, EventArgs e)
{
    var result = client.BeginConnect(ipAddress.Text, Convert.ToInt32(Port.Text), null, null);
    var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1));

    if (success)
    {
        await DisplayAlert("Connected", "The client has successfully connected", "OK");
    }
    else
    {
        await DisplayAlert("Connection Unsuccessful", "The client couldn't connect!", "OK");
    }
}

I tried looking up the issue and the only thing I found was: TcpClient.Connected returns true yet client is not connected, what can I use instead? but, this link is stating that the client.Connected bool remains true after disconnection, while my problem is that it says the client connects even even though the client never gets a true connection to the server.

The project is currently using .NET Standard 2.0


Solution

  • I have found out the reason it would return client.Connected is true is because running the same ConnectAsync/BeginConnect method twice while the client is still trying to connect and hasn't yet timed out will cause the client.Connected value to be true for some reason.

    The only way to fix this it to wait for the timeout to complete, or if the timeout is too long, to dispose the client and create a new one.