Team XSockets.NET

MQTT Samples - Publish & Subscribe 1

This sample contains simple chat where a custom MqttBridge sends incoming MQTT messages to a XSockets controller. Then the XSockets controller sends the message to both XSockets client and MQTT clients. This means that we return false in the OnPublish method on our custom MqttBridge since the actual publish to MQTT is done from within XSockets.

MqttBridge

public class MyMqttBride : MqttBridge
{
    private Chat chat;
    public MyMqttBride()
    {
        chat = new Chat();
    }
    public override bool OnPublish(MqttClient client, MqttMsgPublishEventArgs e)
    {
        //Extract the message to a string
        var m = System.Text.Encoding.UTF8.GetString(e.Message);

        //Pass the message to the Say method on the chat controller.
        chat.Say(m);

        // Deny the message to be published to MQTT clients
        return false;
    }
}

XSockets Controller

public class Chat : XSocketController
{
    public async Task Say(string message)
    {
        //Publish to XSockets clients on chat controller
        await this.PublishToAll(message, "say");
        //Publish to MQTT clients
        this.MqttPublish("say", message);        
    }
}

Result

First we connect both Putty and Mqtt.fx, and they both subscribe to the topic say.

mqtt pubsub 1

Then Putty publish a message to the chat controller and the method say. The message is then received on both clients (Putty and Mqtt.fx)

mqtt pubsub 2

Finally the Mqtt.fx client also publish a message on the topic say. The message is sent to the XSockets controller by the MqttBridge and then all client receives the message.

mqtt pubsub 3

results matching ""

    No results matching ""