MemoryPersistence persistence = new MemoryPersistence();
MqttConnectOptions connOpts = new MqttConnectOptions();
MqttClient client = new MqttClient(broker, clientId, persistence);
client.connect(connOpts);
MqttMessage message = new MqttMessage(content.getBytes());
message.setQos(qos);
client.publish(pub_topic, message);
System.out.println('Message published');
client.subscribe(sub_topic, qos);
System.out.println('Subscribed to topic: ' + sub_topic);
System.out.println('Subscribed to message: ' + message);
void publish(MQTTClient client, char *topic, char *payload) {
MQTTClient_message message = MQTTClient_message_initializer;
message.payload = payload;
message.payloadlen = strlen(payload);
message.qos = QOS;
message.retained = 0;
MQTTClient_deliveryToken token;
MQTTClient_publishMessage(client, topic, &message, &token);
MQTTClient_waitForCompletion(client, token, TIMEOUT);
printf('Send `%s` to topic `%s` ', payload, PUB_TOPIC);
}
def publish(client):
msg_count = 0
while not FLAG_EXIT:
msg_dict = {
'type': 'info'
}
msg = json.dumps(msg_dict)
if not client.is_connected():
logging.error('publish: MQTT client is not connected!')
time.sleep(1)
continue
result = client.publish(PUB_TOPIC, msg)
status = result[0]
if status == 0:
print(f'Send `{msg}` to topic `{PUB_TOPIC}`')
else:
print(f'Failed to send message to topic {PUB_TOPIC}')
msg_count += 1
time.sleep(1)
func publish(client mqtt.Client) {
qos := 0
msgCount := 0
for {
payload := `{'type':'info'}`
if token := client.Publish(pub_topic, byte(qos), false, payload); token.Wait() && token.Error() != nil {
fmt.Printf('publish failed, topic: %s, payload: %s', pub_topic, payload)
} else {
fmt.Printf('publish success, topic: %s, payload: %s', pub_topic, payload)
}
msgCount++
time.Sleep(time.Second * 1)
}
}
client.on('connect', () => {
console.log(`${protocol}: Connected`)
client.subscribe(sub_topic, { qos }, (error) => {
if (error) {
console.log('subscribe error:', error)
return
}
console.log(`${protocol}: Subscribe to topic '${sub_topic}'`)
client.publish(pub_topic, payload, { qos }, (error) => {
if (error) {
console.error(error)
}
})
})
})
static void Publish(MqttClient client, string topic)
{
int msg_count = 0;
while (true)
{
System.Threading.Thread.Sleep(1*1000);
string msg = '{'type':'info'}';
client.Publish(topic, System.Text.Encoding.UTF8.GetBytes(msg));
Console.WriteLine('Send `{0}` to topic `{1}`', msg, topic);
msg_count++;
}
}
$payload = array(
'type' => 'info'
);
$jsonp = json_encode($payload);
$mqtt->publish(
$jsonp,
0,
true
);
printf('msg send $jsonp to $pub_topic');
$mqtt->subscribe($sub_topic, function ($topic, $message) {
printf('Received message on topic [%s]: %s', $topic, $message);
}, 0);