我正在使用 C 语言的 Paho 客户端库编写一个向 mosquitto 代理发布整数的客户端。当我将有效负载设置为字符串时,它发布时没有问题,但是当我将有效负载设置为整数时,发布者崩溃并显示以下消息,如图所示。
我的客户端代码如下:
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "MQTTClient.h"
#define ADDRESS "tcp://localhost:1883"
#define CLIENTID "ExampleClientPub"
#define TOPIC "MQTT Examples"
#define QOS 1
#define TIMEOUT 10000L
int main(int argc, char* argv[])
{
MQTTClient client;
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
MQTTClient_message pubmsg = MQTTClient_message_initializer;
MQTTClient_deliveryToken token;
int rc, ch;
int i = 4;
MQTTClient_create(&client, ADDRESS, CLIENTID,
MQTTCLIENT_PERSISTENCE_NONE, NULL);
conn_opts.username = "user";
conn_opts.password = "hello";
conn_opts.keepAliveInterval = 65000;
conn_opts.cleansession = 1;
if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
{
printf("Failed to connect, return code %d\n", rc);
exit(-1);
}
pubmsg.payload = i;
pubmsg.payloadlen = sizeof(i); //strlen(PAYLOAD);
pubmsg.qos = QOS;
pubmsg.retained = 0;
MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token);
printf("Waiting for up to %d seconds for publication of %d\n"
"on topic %s for client with ClientID: %s\n",
(int)(TIMEOUT / 1000), i, TOPIC, CLIENTID);
rc = MQTTClient_waitForCompletion(client, token, TIMEOUT);
printf("Message with delivery token %d delivered\n", token);
do
{
ch = getchar();
} while (ch != 'Q' && ch != 'q');
MQTTClient_disconnect(client, 10000);
MQTTClient_destroy(&client);
return rc;
}
谁能告诉我我做错了什么?
最佳答案
有效负载
的类型为char *
typedef struct {
char * topic;
char * payload;
unsigned int length;
boolean retained;
} MQTTMessage;
这意味着它只接受字符串。
关于c - Mosquitto 发布者未发布 C 中的整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39280293/