03-request-response-1.c 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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, "response/topic", 0);
  15. }
  16. }
  17. void on_subscribe(struct mosquitto *mosq, void *obj, int mid, int qos_count, const int *granted_qos)
  18. {
  19. mosquitto_property *props = NULL;
  20. mosquitto_property_add_string(&props, MQTT_PROP_RESPONSE_TOPIC, "response/topic");
  21. mosquitto_publish_v5(mosq, NULL, "request/topic", 6, "action", 0, 0, props);
  22. mosquitto_property_free_all(&props);
  23. }
  24. void on_message(struct mosquitto *mosq, void *obj, const struct mosquitto_message *msg)
  25. {
  26. if(!strcmp(msg->payload, "a response")){
  27. run = 0;
  28. }else{
  29. run = 1;
  30. }
  31. }
  32. int main(int argc, char *argv[])
  33. {
  34. int rc;
  35. struct mosquitto *mosq;
  36. int ver = PROTOCOL_VERSION_v5;
  37. int port = atoi(argv[1]);
  38. mosquitto_lib_init();
  39. mosq = mosquitto_new("request-test", true, NULL);
  40. if(mosq == NULL){
  41. return 1;
  42. }
  43. mosquitto_opts_set(mosq, MOSQ_OPT_PROTOCOL_VERSION, &ver);
  44. mosquitto_connect_callback_set(mosq, on_connect);
  45. mosquitto_subscribe_callback_set(mosq, on_subscribe);
  46. mosquitto_message_callback_set(mosq, on_message);
  47. rc = mosquitto_connect(mosq, "localhost", port, 60);
  48. while(run == -1){
  49. rc = mosquitto_loop(mosq, -1, 1);
  50. }
  51. mosquitto_destroy(mosq);
  52. mosquitto_lib_cleanup();
  53. return run;
  54. }