Search code examples
c#xamarinxamarin.formsxamarin.androidxamarin.ios

Why does IAsyncResult.AsyncWaitHandle.WaitOne return false when wifi has no internet connection and mobile data is turned on? (XAMARIN)


I'm trying to do a sync with my custom device via wifi connection. Everything works fine when my mobile data is turned off, but when it's turned on it won't work (because my custom device has no connection to the internet).

This is where the problem happens:

stateSuccess = true;
tcpclnt = new TcpClient();
IAsyncResult ar = tcpclnt.BeginConnect(ip, port, new AsyncCallback(connectCallback), stateSuccess);
int timeout = 3000;
stateSuccess = ar.AsyncWaitHandle.WaitOne(timeout, false);

when I have mobile data turned on stateSuccess = false, but when mobile data is turned off stateSuccess = true. I'm always connected over wifi to my custom device.

My connectCallback is:

private void connectCallback(IAsyncResult ar)
        {
            var stateSuccess = (Boolean)ar.AsyncState;

            try
            {
                tcpclnt.EndConnect(ar);
            }
            catch (Exception exc)
            {
                //handle
            }

            try
            {
                if (tcpclnt != null && tcpclnt.Connected && stateSuccess)
                    return;

                tcpclnt.Close();
            }
            catch (Exception exc)
            {
                if (tcpclnt != null)
                    tcpclnt.Close();
            }
        }

I think the problem is somewhere in it chosing the wrong network. How can I force it to use wifi network even thou the wifi has no internet connection?


Solution

  • The devices do not care nor discriminate the lower-level base-band radio scanning (we're talking about telephony here), that is left to the actual radio firmware to deal with.

    If you dont want to use WIFI, turn it off. But if you want to force use WIFI, just turn your cellular data off

    Edit: I just found a workaround to this that works ONLY for Android : https://stackoverflow.com/a/56590566/11104068