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