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

问题描述 投票:0回答:1

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

[使用TcpClient.ConnectAsync时,除非我按两次运行Button_Clicked下代码的按钮,否则它不会返回true,但是使用TcpClient.BeginConnect时,client.Connected始终返回true。我知道客户端未连接,因为我有一个检测系统,当连接断开时,该系统会将用户踢到重新连接页面。

我在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?,但是,此链接说明客户端。断开连接后,布尔连接仍然为真,而我的问题是,即使客户端永远不会与服务器建立真正的连接。

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

android networking xamarin.forms tcp .net-standard-2.0
1个回答
0
投票

我已经发现返回客户端的原因。Connected为true是因为在客户端仍尝试连接且尚未超时的情况下,两次运行相同的ConnectAsync / BeginConnect方法将导致client.Connected值为由于某些原因,为true。

© www.soinside.com 2019 - 2024. All rights reserved.