How to setup PUB/SUB NetMQ in Xamarin Forms

400 Views Asked by At

I have a Windows Services running as a Publisher and I am trying to setup Xamarin Forms as the Subscriber. The code below works just fine in a Console App or LinqPad, but when copied and pasted into Xamarin Forms, the SubscriberSocket just does not respond to messages from the server.

Do you know how to wire this up?

I am using NetMQ v 4.0.0.1

public partial class MainPage : ContentPage
{
    public MainPage()
    {
        InitializeComponent();
        Task.Run(() => StartPubSubSocketSubscriber());
    }

    private void StartPubSubSocketSubscriber()
    {
        string topic = "TopicA";

        using (var subSocket = new SubscriberSocket())
        {
            subSocket.Options.ReceiveHighWatermark = 1000;
            subSocket.Connect("tcp://192.168.30.120:5556");
            subSocket.Subscribe(topic);

            while (true)
            {
                string messageTopicReceived = subSocket.ReceiveFrameString();
                string messageReceived = subSocket.ReceiveFrameString();

                Device.BeginInvokeOnMainThread(() =>
                {
                    label.Text = messageReceived;
                });
            }
        }
    }
}

I also tried starting the background thread with Task.Factory.StartNew(() => StartPubSubSocketSubscriber(), TaskCreationOptions.LongRunning); but it is just as unresponsive to messages from the publisher.

Thank you.

PS.: removed subSocket.Connect("tcp://localhost:5556");

1

There are 1 best solutions below

0
On BEST ANSWER

The fix for this was a 2 step process:

  1. The SubscriberSocket was incorrectly pointing to localhost. An understandable mistake since the emulator runs on the same machine as the server application. Make sure the Subscriber has the explicit IP address when running on a virtual environment or another device.
  2. The issue with SubscriberSocket not responding was actually on a server. I had set it up with pubSocket.Bind("tcp://localhost:5556");, once I changed it to pubSocket.Bind("tcp://*:5556"); the SubscriberSocket started responding. This is an error in documentation.

The hint to the solution came from the NetMQ github issue tracking: https://github.com/zeromq/netmq/issues/747