客户端库支持两种操作模式,称为同步模式和异步模式。如果你的应用程序调用了MQTTClient_setCallbacks(),则客户端将会进入异步模式,否则会以同步模式运行。
同步模式下,客户端应用程序运行在单个线程上。信息的发布使用MQTTClient_publish()和MQTTClient_publishMessage()函数。为了确定Qos1和Qos2(详见Quality of service)的信息已经成功传递,应用程序必须调用MQTTClient_waitForCompletion()这个函数。一个展示同步发布的例子可查看Synchronous publication example。同步模式下接收信息使用 MQTTClient_receive()函数,客户端应用程序必须相对频繁地调用 MQTTClient_receive()或MQTTClient_yield(),以便允许(执行)确认和保持与服务器的网络连接的 MQTT "ping"这些操作。
异步模式下,客户端应用程序运行在若干个线程上。如同同步模式,(异步模式中)主程序调用客户端库中的函数来发布和订阅,而在在后台进行握手和维持网络连接这些操作。客户端应用程序通过调用 MQTTClient_setCallbacks()( (详情请见MQTTClient_messageArrived(), MQTTClient_connectionLost()和 MQTTClient_deliveryComplete()))来使用库进行回调注册而获得状态通知和消息接收。然而, 这个 API 不是线程安全的-不可能从多个线程调用它而不进行同步。你可以使用MQTTAsync API来完成此操作。
接下使用MQTTAsync系列函数来实现publish和subscribe:
publish端:
#include
#include
#include
#include "MQTTAsync.h"
#include
#define ADDRESS "tcp://localhost:1883"
#define CLIENTID "ExampleClientPub"
#define TOPIC "MQTT Examples"
#define PAYLOAD "Hello World!"
#define QOS 1
#define TIMEOUT 10000L
volatile MQTTAsync_token deliveredtoken;
int finished = 0;
void connlost(void *context, char *cause)
{
MQTTAsync client = (MQTTAsync)context;
MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
int rc;
printf("\nConnection lost\n");
printf(" cause: %s\n", cause);
printf("Reconnecting\n");
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start connect, return code %d\n", rc);
finished = 1;
}
}
void onDisconnect(void* context, MQTTAsync_successData* response)
{
printf("Successful disconnection\n");
finished = 1;
}
void onSend(void* context, MQTTAsync_successData* response)
{
MQTTAsync client = (MQTTAsync)context;
MQTTAsync_disconnectOptions opts = MQTTAsync_disconnectOptions_initializer;
int rc;
printf("Message with token value %d delivery confirmed\n", response->token);
opts.onSuccess = onDisconnect;
opts.context = client;
if ((rc = MQTTAsync_disconnect(client, &opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start sendMessage, return code %d\n", rc);
exit(EXIT_FAILURE);
}
}
void onConnectFailure(void* context, MQTTAsync_failureData* response)
{
printf("Connect failed, rc %d\n", response ? response->code : 0);
finished = 1;
}
void onConnect(void* context, MQTTAsync_successData* response)
{
MQTTAsync client = (MQTTAsync)context;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
int rc;
printf("Successful connection\n");
opts.onSuccess = onSend;
opts.context = client;
pubmsg.payload = PAYLOAD;
pubmsg.payloadlen = (int)strlen(PAYLOAD);
pubmsg.qos = QOS;
pubmsg.retained = 0;
deliveredtoken = 0;
if ((rc = MQTTAsync_sendMessage(client, TOPIC, &pubmsg, &opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start sendMessage, return code %d\n", rc);
exit(EXIT_FAILURE);
}
}
int main(int argc, char* argv[])
{
MQTTAsync client;
MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
int rc;
MQTTAsync_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
MQTTAsync_setCallbacks(client, NULL, connlost, NULL, NULL);
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
conn_opts.onSuccess = onConnect;
conn_opts.onFailure = onConnectFailure;
conn_opts.context = client;
if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start connect, return code %d\n", rc);
exit(EXIT_FAILURE);
}
printf("Waiting for publication of %s\n"
"on topic %s for client with ClientID: %s\n",
PAYLOAD, TOPIC, CLIENTID);
while (!finished)
#if defined(WIN32)
Sleep(100);
#else
usleep(10000L);
#endif
MQTTAsync_destroy(&client);
return rc;
}
subscribe端:
#include
#include
#include
#include "MQTTAsync.h"
#include
#define ADDRESS "tcp://localhost:1883"
#define CLIENTID "ExampleClientSub"
#define TOPIC "MQTT Examples"
#define PAYLOAD "Hello World!"
#define QOS 1
#define TIMEOUT 10000L
volatile MQTTAsync_token deliveredtoken;
int disc_finished = 0;
int subscribed = 0;
int finished = 0;
void connlost(void *context, char *cause)
{
MQTTAsync client = (MQTTAsync)context;
MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
int rc;
printf("\nConnection lost\n");
if (cause)
printf(" cause: %s\n", cause);
printf("Reconnecting\n");
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start connect, return code %d\n", rc);
finished = 1;
}
}
int msgarrvd(void *context, char *topicName, int topicLen, MQTTAsync_message *message)
{
int i;
char* payloadptr;
printf("Message arrived\n");
printf(" topic: %s\n", topicName);
printf(" message: ");
payloadptr = message->payload;
for(i=0; i<message->payloadlen; i++)
{
putchar(*payloadptr++);
}
putchar('\n');
MQTTAsync_freeMessage(&message);
MQTTAsync_free(topicName);
return 1;
}
void onDisconnect(void* context, MQTTAsync_successData* response)
{
printf("Successful disconnection\n");
disc_finished = 1;
}
void onSubscribe(void* context, MQTTAsync_successData* response)
{
printf("Subscribe succeeded\n");
subscribed = 1;
}
void onSubscribeFailure(void* context, MQTTAsync_failureData* response)
{
printf("Subscribe failed, rc %d\n", response ? response->code : 0);
finished = 1;
}
void onConnectFailure(void* context, MQTTAsync_failureData* response)
{
printf("Connect failed, rc %d\n", response ? response->code : 0);
finished = 1;
}
void onConnect(void* context, MQTTAsync_successData* response)
{
MQTTAsync client = (MQTTAsync)context;
MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
int rc;
printf("Successful connection\n");
printf("Subscribing to topic %s\nfor client %s using QoS%d\n\n"
"Press Q to quit\n\n" , TOPIC, CLIENTID, QOS);
opts.onSuccess = onSubscribe;
opts.onFailure = onSubscribeFailure;
opts.context = client;
deliveredtoken = 0;
if ((rc = MQTTAsync_subscribe(client, TOPIC, QOS, &opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start subscribe, return code %d\n", rc);
exit(EXIT_FAILURE);
}
}
int main(int argc, char* argv[])
{
MQTTAsync client;
MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
MQTTAsync_disconnectOptions disc_opts = MQTTAsync_disconnectOptions_initializer;
int rc;
int ch;
MQTTAsync_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
MQTTAsync_setCallbacks(client, client, connlost, msgarrvd, NULL);
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
conn_opts.onSuccess = onConnect;
conn_opts.onFailure = onConnectFailure;
conn_opts.context = client;
if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start connect, return code %d\n", rc);
exit(EXIT_FAILURE);
}
while (!subscribed)
#if defined(WIN32)
Sleep(100);
#else
usleep(10000L);
#endif
if (finished)
goto exit;
do
{
ch = getchar();
} while (ch!='Q' && ch != 'q');
disc_opts.onSuccess = onDisconnect;
if ((rc = MQTTAsync_disconnect(client, &disc_opts)) != MQTTASYNC_SUCCESS)
{
printf("Failed to start disconnect, return code %d\n", rc);
exit(EXIT_FAILURE);
}
while (!disc_finished)
#if defined(WIN32)
Sleep(100);
#else
usleep(10000L);
#endif
exit:
MQTTAsync_destroy(&client);
return rc;
}
编译同样要加上头文件,动态库,运行时可能也需要导入环境变量。
zhanghang@Ubuntu-14:~/MQTT/paho.mqtt.c/build/output/samples$ ./MQTTAsync_publish
Waiting for publication of Hello World!
on topic MQTT Examples for client with ClientID: ExampleClientPub
Successful connection
Message with token value 1 delivery confirmed
Successful disconnection
zhanghang@Ubuntu-14:~/MQTT/paho.mqtt.c/build/output/samples$ ./MQTTAsync_subscribe
Successful connection
Subscribing to topic MQTT Examples
for client ExampleClientSub using QoS1
Press Q to quit
Subscribe succeeded
Message arrived
topic: MQTT Examples
message: Hello World!
客户端成功推送话题和订阅话题。
使用mosquitto分别测试publish和subscribe成功
zhanghang@Ubuntu-14:~/MQTT/paho.mqtt.c/build/output/samples$ ./MQTTAsync_publish
Waiting for publication of Hello World!
on topic MQTT Examples for client with ClientID: ExampleClientPub
Successful connection
Message with token value 1 delivery confirmed
Successful disconnection
zhanghang@Ubuntu-14:~/MQTT/paho.mqtt.c/build/output/samples$ mosquitto_sub -h 127.0.0.1 -p 1883 -v -t "MQTT Examples"
MQTT Examples Hello World!
zhanghang@Ubuntu-14:~/MQTT/paho.mqtt.c/build/output/samples$ mosquitto_pub -h 127.0.0.1 -p 1883 -t "MQTT Examples" -m "Hello World"
zhanghang@Ubuntu-14:~/MQTT/paho.mqtt.c/build/output/samples$ ./MQTTAsync_subscribe
Successful connection
Subscribing to topic MQTT Examples
for client ExampleClientSub using QoS1
Press Q to quit
Subscribe succeeded
Message arrived
topic: MQTT Examples
message: Hello World
使用mqtt.fx应用程序测试软件成功
使用mqtt.fx订阅话题:
zhanghang@Ubuntu-14:~/MQTT/paho.mqtt.c/build/output/samples$ ./MQTTAsync_publish
Waiting for publication of Hello World!
on topic MQTT Examples for client with ClientID: ExampleClientPub
Successful connection
Message with token value 1 delivery confirmed
Successful disconnection
zhanghang@Ubuntu-14:~/MQTT/paho.mqtt.c/build/output/samples$ ./MQTTAsync_subscribe
Successful connection
Subscribing to topic MQTT Examples
for client ExampleClientSub using QoS1
Press Q to quit
Subscribe succeeded
Message arrived
topic: MQTT Examples
message: hello