2023-10-24 17:19:13 +08:00
|
|
|
#include <mosquitto.h>
|
|
|
|
#include <stdbool.h>
|
|
|
|
#include <stdio.h>
|
|
|
|
#include <stdlib.h>
|
|
|
|
#include <string.h>
|
|
|
|
int isConnected = 0;
|
2023-10-26 19:38:47 +08:00
|
|
|
void connect_callback(struct mosquitto *mosq, void *obj, int rc)
|
|
|
|
{
|
|
|
|
if (rc == 0)
|
|
|
|
{
|
2023-10-24 17:19:13 +08:00
|
|
|
printf("---连接服务器成功---\n");
|
|
|
|
isConnected = 1;
|
|
|
|
}
|
|
|
|
}
|
2023-10-26 19:38:47 +08:00
|
|
|
int main(int argc, char const *argv[])
|
|
|
|
{
|
|
|
|
if (argc < 3)
|
|
|
|
{
|
2023-10-24 17:19:13 +08:00
|
|
|
printf("format: ./pub1 msgid topic msg");
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
mosquitto_lib_init();
|
2023-10-26 19:38:47 +08:00
|
|
|
struct mosquitto *client = mosquitto_new(NULL, true, NULL);
|
2023-10-24 17:19:13 +08:00
|
|
|
mosquitto_connect_callback_set(client, connect_callback);
|
|
|
|
mosquitto_connect(client, "10.12.156.19", 1883, 60);
|
|
|
|
mosquitto_loop_start(client);
|
|
|
|
while (isConnected == 0)
|
2023-10-26 19:38:47 +08:00
|
|
|
;
|
|
|
|
int msg_id = atoi(argv[1]);
|
|
|
|
char *topic = (char *)argv[2];
|
|
|
|
char *msg = (char *)argv[3];
|
2023-10-24 17:19:13 +08:00
|
|
|
int flag =
|
|
|
|
mosquitto_publish(client, &msg_id, topic, strlen(msg), msg, 1, true);
|
2023-10-26 19:38:47 +08:00
|
|
|
if (flag == MOSQ_ERR_SUCCESS)
|
|
|
|
{
|
2023-10-24 17:19:13 +08:00
|
|
|
printf("---消息发布成功: %s(%d):%s---\n", topic, msg_id, msg);
|
|
|
|
mosquitto_destroy(client);
|
|
|
|
mosquitto_lib_cleanup();
|
|
|
|
}
|
|
|
|
return 0;
|
|
|
|
}
|