03-request-response-2.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include <stdbool.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <mosquitto.h>
  6. #include <mqtt_protocol.h>
  7. static int run = -1;
  8. static int sent_mid = -1;
  9. void on_connect(struct mosquitto *mosq, void *obj, int rc)
  10. {
  11. if(rc){
  12. exit(1);
  13. }else{
  14. mosquitto_subscribe(mosq, NULL, "request/topic", 0);
  15. }
  16. }
  17. void on_message_v5(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg, const mosquitto_property *props)
  18. {
  19. const mosquitto_property *p_resp, *p_corr = NULL;
  20. char *resp_topic = NULL;
  21. int rc;
  22. if(!strcmp(msg->topic, "request/topic")){
  23. p_resp = mosquitto_property_read_string(props, MQTT_PROP_RESPONSE_TOPIC, &resp_topic, false);
  24. if(p_resp){
  25. p_corr = mosquitto_property_read_binary(props, MQTT_PROP_CORRELATION_DATA, NULL, NULL, false);
  26. rc = mosquitto_publish_v5(mosq, NULL, resp_topic, strlen("a response"), "a response", 0, false, p_corr);
  27. free(resp_topic);
  28. }
  29. }
  30. }
  31. void on_publish(struct mosquitto *mosq, void *obj, int mid)
  32. {
  33. run = 0;
  34. }
  35. int main(int argc, char *argv[])
  36. {
  37. int rc;
  38. struct mosquitto *mosq;
  39. int ver = PROTOCOL_VERSION_v5;
  40. int port = atoi(argv[1]);
  41. mosquitto_lib_init();
  42. mosq = mosquitto_new("response-test", true, NULL);
  43. if(mosq == NULL){
  44. return 1;
  45. }
  46. mosquitto_opts_set(mosq, MOSQ_OPT_PROTOCOL_VERSION, &ver);
  47. mosquitto_connect_callback_set(mosq, on_connect);
  48. mosquitto_publish_callback_set(mosq, on_publish);
  49. mosquitto_message_v5_callback_set(mosq, on_message_v5);
  50. rc = mosquitto_connect(mosq, "localhost", port, 60);
  51. while(run == -1){
  52. rc = mosquitto_loop(mosq, -1, 1);
  53. }
  54. mosquitto_destroy(mosq);
  55. mosquitto_lib_cleanup();
  56. return run;
  57. }