Click or drag to resize

MqttClient Class

MQTT client socket.
Inheritance Hierarchy
SystemObject
  Demo3D.HLE.Comms.NetMqttClient

Namespace:  Demo3D.HLE.Comms.Net
Assembly:  Demo3D.HLE (in Demo3D.HLE.dll) Version: 18.03.00
Syntax
C#
public static class MqttClient

The MqttClient type exposes the following members.

Methods
  NameDescription
Public methodStatic memberCode exampleOpen
Opens an MQTT client connection.
Public methodStatic memberCode exampleOpenAsync
Opens an MQTT client connection.
Top
Remarks
Examples

The following example shows a simple MQTT client that connects to a configured server, subscribes to a topic filter, and publishes a message to that topic once per second, making full use of the publish-subscribe pattern.

C#
using System;
using System.Collections;
using System.Threading.Tasks;
using Demo3D.IO;
using Demo3D.Native;
using Demo3D.Net;
using Demo3D.Net.Protocols;
using Demo3D.Visuals;

namespace Examples.Net.CotpClientExample {
    [Auto] public class Client {
        [Auto] IBuilder                    app;
        [Auto] PrintDelegate               print;
        [Auto] SimplePropertyValue<string> cotpAddress;  // The hostname to connect to.
        [Auto] SimplePropertyValue<string> cotpTsap;     // The tsap to connect to.

        [Auto] IEnumerable OnInitialize(Visual sender) {
            yield return Connect();
        }

        async Task Connect() {
            Client<IPacketIOService> cotpClient = null;

            try {
                // Connect to the server using the configured cotpAddress and cotpTsap.
                cotpClient = await CotpClient.OpenAsync(sync: false, cotpAddress, cotpTsap);

                // Start sending messages to the server.
                await SendMessages(cotpClient);
            }
            catch (Exception e) {
                // If there's an error, close the connection and report the error.
                cotpClient?.Close(e);
            }
        }

        async Task SendMessages(Client<IPacketIOService> cotpClient) {
            // Send a message to the server once a second while the model is running.
            for (int msg = 0; app.Running; msg++) {
                // Construct a packet.
                var writer = new BufferWriter();
                writer.WriteInt32LE(msg);  // Fill the packet with our message - a 32bit integer.
                var buffer = writer.Resolve();

                // Send the packet data.
                await cotpClient.IO.WriteAsync(buffer);

                // Wait one second.
                await Task.Delay(1000);
            }
        }
    }
}
See Also