Monthly Archives: March 2016

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

Signing your Xamarin.Android application package during the development phase

When you create an application using Xamarin.Android (or even if you use other tools such as Android Studio), it’s necessary to sign the application package (APK) to publish your application on the Google Play Store.

If you don’t know how how to proceed, Xamarin has published a step-by-step tutorial which explains how to achieve this goal.

This article is very useful when your application is finished, because it explains how to use the built-in tools to archive, sign and distribute your application.

But when you’re still in the development phase (e.g. to implement and test push notifications), it’s not convenient to use this workflow.

Fortunately, a more simple way to reach the same goal exist and is very easy to implement. Let’s take a look to this process.

Create a new keystore/certificate

The first step to sign an application is to generate a keystore, the container for the certificate associated to your application.

There are different ways to generate a keystore (e.g. command-line tools), but my preferred way is to use the GUI available in Xamarin Studio. To access this screen, go to Xamarin Studio > Preferences > Android Signing Keys.

Xamarin - Android Signing Keys

This screen lists all the keystores that you created on your computer. You are also able to import an existing keystore, or generate a new one by clicking to Create a new key.

When you create a new new key, you just have to complete some information on who you are (firstname, lastname, organisation…) and the security of your certificate (alias, password and validity).

Xamarin - Android Create Keystore

Once you created the new key, it’s stored in the folder ~/Library/Developer/Xamarin/Keystore/Your-Alias (if you’re using a Mac).

Sign your package with the keystore

The second (and last) step to sign your package is to associate the keystore to your project.

Once your project is open in Xamarin Studio, go to Project Options > Android Package Signing.

Check the box labeled “Sign the .APK file using the following keystore details” and fill the details with information used when you created the keystore.

If you have used the GUI to create the keystore, you probably noticed that there’s only one password value while there are 2 values (keystore password and alias password) in this screen. The GUI use the same value for both fields, but it’s possible to use different values if you use command-line tools.

Xamarin - Android Package Signing

Please note that it’s possible to use different keystores for debug and release modes. You can switch between these modes using the configuration list on the top of the dialog box.