Skip to content
Chris Tacke edited this page Sep 10, 2017 · 1 revision

Here's a simple unit test that shows creating a client, subscribing to a topic, publishing to a topic, and handling incoming data from a subscription.

[TestMethod()]
public void ClientReceiveTest()
{
    var receivedMessage = false;

    // create the client
    var client = new MQTTClient("test.mosquitto.org", 1883);

    // hook up the MessageReceived event with a handler
    client.MessageReceived += (topic, qos, payload) =>
    {
        Debug.WriteLine("RX: " + topic);
        receivedMessage = true;
    };

    var i = 0;
    // connect to the MQTT server
    client.Connect("OpenNETCF");
    // wait for the connection to complete
    while (!client.IsConnected)
    {
        Thread.Sleep(1000);

        if (i++ > 10) Assert.Fail();
    }

    Assert.IsTrue(client.IsConnected);

    // add a subscription
    client.Subscriptions.Add(new Subscription("OpenNETCF/#"));

    i = 0;
    while (true)
    {
        if (receivedMessage) break;

        Thread.Sleep(1000);

        // publish on our own subscribed topic to see if we hear what we send
        client.Publish("OpenNETCF/Test", "Hello", QoS.FireAndForget, false);

        if (i++ > 10) break;
    }

    Assert.IsTrue(receivedMessage);
}
Clone this wiki locally