displayname
displayname

Reputation: 61

Android only: C# .net-MAUI, not Xamarin(!), sending UDP?

Situation:
VS 2022, 17.0.4
Maui App,
net6.0-android

AndroidManifest.xml contains also:
android.permission.INTERNET
android.permission.CHANGE_NETWORK_STATE
android.permission.ACCESS_WIFI_STATE
android.permission.CHANGE_WIFI_MULTICAST_STATE
android.permission.CHANGE_WIFI_STATE

Connected mobile Phone:
Samsung SM-G960F (Android 10.0 - API 29)

OS: Windows 11, latest patch.

All firewalls are down (for testing purpose only!)
While debugging the develop computer is only connected to a Wifi network; computers ethernet card is disabled.
Mobile phone is connected to this dev computer via USB cable (to be able to debug) and to the same Wifi network as the computer.

App starts and works fine, app can be debugged. No issue at all - except:
After the application is fully initialized and ready to accept user interactions -> Click on button -> Desired method is called -> Code is worked out -> The code should make a simple UDP call but it does not (or the packet does not reach the UDP listener due to missing configuration?).

The UDP receiver works fine and is capable to receive UDP packets.
My mobile phone and the UDP receiver app are using the same port.

I read/found already that in the previous cross-platform framework, means “Xamarin (Android SDK 12)”, some permissions must be set (I did, see above) and that the multicastlock must be set over the WifiManager …
I tried this in my MAUI app. But could not find anything guiding me nor figured it out by myself.

My MAUI sending code:

var dataToBeSend = "What ever ...";   
var data = Encoding.UTF8.GetBytes(dataToBeSend);
var UdpClient = new UdpClient();
// UdpClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true);
UdpClient.ExclusiveAddressUse = false;
UdpClient.EnableBroadcast = true;
// UdpClient.Client.Bind(new IPEndPoint(IPAddress.Parse("255.255.255.255"), BroadcastPort));
// UdpClient.Client.Bind(new IPEndPoint(IPAddress.Any, BroadcastPort));
UdpClient.Send(data, data.Length, "255.255.255.255", BroadcastPort);

As said: very easy and straight forward.
Notice that I also tried binding UDP code …

So please can someone be so kind to guide me or give me a hint?

Thank you very much in advance!

Upvotes: 1

Views: 1403

Answers (1)

displayname
displayname

Reputation: 61

ANSWER:

After two days I found a solution - and would like to share it because may be it helps someone else.

The code to make the UDP call msut be placed in a THREAD (not task!)
codesnippet:

var communication = new Communication();
var udpThread = new Thread(new ThreadStart(communication.FireUDPCall));
udpThread.Start();

The firewalls can stay turned on / active!

Upvotes: 1

Related Questions