02-unsubscribe-multiple-v5.c 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include <stdbool.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <mosquitto.h>
  5. static int run = -1;
  6. void on_connect(struct mosquitto *mosq, void *obj, int rc)
  7. {
  8. if(rc){
  9. exit(1);
  10. }else{
  11. mosquitto_subscribe(mosq, NULL, "unsubscribe/test", 2);
  12. }
  13. }
  14. void on_subscribe(struct mosquitto *mosq, void *obj, int mid, int sub_count, const int *subs)
  15. {
  16. char *unsubs[] = {"unsubscribe/test", "no-sub"};
  17. mosquitto_unsubscribe_multiple(mosq, NULL, 2, unsubs, NULL);
  18. }
  19. void on_disconnect(struct mosquitto *mosq, void *obj, int rc)
  20. {
  21. run = rc;
  22. }
  23. void on_unsubscribe(struct mosquitto *mosq, void *obj, int mid)
  24. {
  25. mosquitto_disconnect(mosq);
  26. }
  27. int main(int argc, char *argv[])
  28. {
  29. int rc;
  30. struct mosquitto *mosq;
  31. int port = atoi(argv[1]);
  32. mosquitto_lib_init();
  33. mosq = mosquitto_new("unsubscribe-test", true, NULL);
  34. if(mosq == NULL){
  35. return 1;
  36. }
  37. mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5);
  38. mosquitto_connect_callback_set(mosq, on_connect);
  39. mosquitto_disconnect_callback_set(mosq, on_disconnect);
  40. mosquitto_subscribe_callback_set(mosq, on_subscribe);
  41. mosquitto_unsubscribe_callback_set(mosq, on_unsubscribe);
  42. rc = mosquitto_connect(mosq, "localhost", port, 60);
  43. while(run == -1){
  44. mosquitto_loop(mosq, -1, 1);
  45. }
  46. mosquitto_destroy(mosq);
  47. mosquitto_lib_cleanup();
  48. return run;
  49. }