Broadcast messages over the network from your Xamarin application

Since few days, I think and look for the best technical solutions to create a new tool to include in my mobile application development toolkit.

This tool requires, when a mobile application (let’s call it client) starts/stops on a device in the same network as my development machine, to send information over the network, to inform other applications (let’s call them listeners) that a new client is started and available on the network.

The “classic” way to achieve this goal is to create a webservice, an call it when the application starts/stops. It’s easy to do but in that case, it’s necessary to store the data sent over the network (e.g. a device identifier), and the listeners need to poll the webservice, to detect new clients.

It’s a good solution in some cases, but not what I want for my tool. I prefer to be notified in real-time when a new client is started/stopped and I don’t want to create a database to store information about clients (in-memory storage is enough).

Then I remembered that it’s possible to broadcast messages over the network through UDP (User Datagram Protocol).

Let’s take a look to this solution to check if it works with Xamarin.

UDP protocol / UdpClient class

UDP is a transport layer protocol defined for use with the IP network layer protocol. This is an unreliable service that provides no guarantees for delivery, packets order and no protection as TCP does (e.g. send an acknowledgment after that a packet was sent and received over the network, otherwise retry to send it). The simplicity of UDP reduces the overhead from using the protocol and the services may be adequate in many cases.

To use UDP from a .NET / Xamarin application, wether to create clients or listeners, the .NET framework offers an UdpClient class which covers all the needs (send, receive, broadcast, multicast, etc…).

Enough of theory, let’s go to the code 🙂

Create a simple UDP listener in C#

To test that we can use UDP from a Xamarin application, we first need to create a listener that will receive the messages sent by the application. To do this, I created on a PC, a console application with the following code :

using System;
using System.Net.Sockets;
using System.Text;

namespace UdpListenerDemo
{
  class MainClass
  {
    public static void Main(string[] args)
    {
      var listener = new UdpListener();
      listener.StartListening();
      Console.ReadLine();
    }
  }

  class UdpListener
  {
    private readonly UdpClient _udpClient = new UdpClient(15000);

    public async void StartListening()
    {
      while(true)
      {
        var result = await _udpClient.ReceiveAsync();
        var message = Encoding.ASCII.GetString(result.Buffer);
        Console.WriteLine(message);
      }
    }
  }
}

This console application will listen for all messages sent over the network through UDP, on port number 15000. When a message is received, it’s printed in the console.

Send messages over the network from Xamarin.iOS

The next part is to create a Xamarin application (a client) that will send messages over the network. For this part, I used the “Single View App” template and put a button on the main screen. Each time the user will tap the button, the application will send a message over the network.

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using UIKit;

namespace UdpClientDemo
{
  public partial class ViewController : UIViewController
  {
    public ViewController(IntPtr handle) : base(handle)
    {
    }

    public override void ViewDidLoad()
    {
      base.ViewDidLoad();
    }

    public override void DidReceiveMemoryWarning()
    {
      base.DidReceiveMemoryWarning();
    }
 
    async partial void SendMessage(UIButton sender)
    {
      using(var client = new UdpClient())
      {
        client.EnableBroadcast = true;
        var endpoint = new IPEndPoint(IPAddress.Broadcast, 15000);
        var message = Encoding.ASCII.GetBytes("Hello World - " + DateTime.Now.ToString());
        await client.SendAsync(message, message.Length, endpoint);
        client.Close();
      }
    }
  }
}

The most important part of the code above, is the declaration of the endpoint. As you can see, we use the same port number (15000) that is declared in the listener, and we use the broadcast address instead of a specific IP address (because we don’t want to target a particular client).

For this sample, I used a Xamarin.iOS application but it also works with Xamarin.Android.

Use the listener and the client

Now that we have all the necessary parts, we can execute our Xamarin application (the client) to see if it works. As you can see on this screenshot, the interface is pretty simple.

Xamarin - UDP Client

If you tap on the “Send UDP Message” button, and if the listener is not started, nothing will happen. The message will be sent over the network but nobody will receive it.

Now if we execute the listener (our console application) then tap the button on the client (our Xamarin application), the message is sent over the network, then received and printed on the console as you can see below.

Xamarin - UDP Listener

Limitations

As we saw in this article, the solution based on UDP to broadcast messages over the network, can be used in Xamarin applications and it’s very easy to implement. But there are some limitations to understand if you use this solution.

The most important is that broadcast messages, generally don’t go through routers. It means that this solution only works if the listeners and the clients are on the same network segment.

Another limitation concerns the UDP protocol. As mentioned earlier, UDP is not reliable and it’s not guaranteed that a message will be delivered. It’s not guaranteed too, that messages are delivered in the same order where they were sent. It also may happen that a message is received many times. For all these cases, your application is responsible to react as you need.

But in my case, I just need to send a message when an application starts/stops. Because my need is very basic, this solution seems to be viable.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s