TcpClient.ConnectAsync 和 TcpClient.BeginConnect 始终在 Xamarin.Forms Android 应用程序中返回 true

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

我在我的 Xamarin.Forms 项目中创建了一个应用程序,我可以在其中使用 TCP 连接将我的 Android phone 连接到我的计算机。我发现在同时使用 TcpClient.ConnectAsync 和 TcpClient.BeginConnect 时,它们都 return 即使端口未打开, client.Connected 也是正确的。我已经验证了这一点,因为我尝试了随机 IP 和随机端口,它仍然说连接成功。

当使用 TcpClient.ConnectAsync 时,它不会 return 正确,除非我按下运行 Button_Clicked 下的代码的按钮 2 次,但是当使用 TcpClient.BeginConnect 时, client.Connected 总是 return 正确。我知道客户端未连接的事实,因为我有一个检测系统,当连接丢失时将用户踢到重新连接页面。

我在 MainPage.xaml.cs 中的 TCPClient 代码:

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");
    }
}

我也尝试过使用 How to set the timeout for a TcpClient? 中的 TcpClient.BeginConnect:

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");
    }
}

我试着查找这个问题,我唯一发现的是:TcpClient.Connected returns true yet client is not connected, what can I use instead? 但是,这个 link 是说 client.Connected bool 在断开连接后仍然为真,而我的问题是它说即使客户端从未真正连接到服务器,客户端也会连接。

该项目目前正在使用 .NET Standard 2.0

我发现它 return client.Connected 是真的原因是因为 运行 相同的 ConnectAsync/BeginConnect 方法两次,而客户端仍在尝试连接并且由于某种原因尚未超时将导致 client.Connected 值为真。

解决此问题的唯一方法是等待超时完成,或者如果超时太长,则处理客户端并创建一个新客户端。