Team XSockets.NET

MQTT Samples - Publish & Subscribe 2

This Publish/Subscribe sample is a more dynamic example. The XSockets controller has no logic here and we instead do all our sending form the MqttBridge.

Another big difference here is that we use topic hierarchies instead of just a simple topic. In this scenario we subscribe to sensor data on the topic home/+/temp. The + wildcard means that we will get data published for all levels matching. Some example are:

  • home/kitchen/temp
  • home/garage/temp

You will NOT get a message for home/basement/laundry/temp since the + is a wildcard for one level.


public class MyMqttBride : MqttBridge
    private Sensor sensor;
    public MyMqttBride()
        sensor = new Sensor();
    public override bool OnPublish(MqttClient client, MqttMsgPublishEventArgs e)
        //Extract the message (we assume that it is JSON being sent in this sample)
        var s = System.Text.Encoding.UTF8.GetString(e.Message);
        //Create a IMessage
        var m = new Message(s, e.Topic);

        //Pusblih to XSockets and MQTT
        sensor.MqttPublish(e.Topic, s);

        // Deny the message to be published to MQTT clients (we already published)
        return false;

XSockets Controller

The sensor controller can ofcourse have methods and logic, but in this sample it is not needed.

public class Sensor : XSocketController


First we connect both Putty and Mqtt.fx, and they both subscribe to the topic home/+/temp.

mqtt pubsub 21

Then the Mqtt.fx client publish a message on the topic home/kitchen/temp and pass some JSON as payload.

mqtt pubsub 22

The message is received at the MqttBridge. The bridge then publish to both XSockets clients and MQTT clients.

mqtt pubsub 23

Note that we did not have to publish to MQTT clients, we could just have been returning true instead of false.

results matching ""

    No results matching ""