amqp_listenq.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Copyright 2007 - 2021, Alan Antonuk and the rabbitmq-c contributors.
  2. // SPDX-License-Identifier: mit
  3. #include <stdint.h>
  4. #include <stdio.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. #include <rabbitmq-c/amqp.h>
  8. #include <rabbitmq-c/tcp_socket.h>
  9. #include <assert.h>
  10. #include "utils.h"
  11. int main(int argc, char const *const *argv) {
  12. char const *hostname;
  13. int port, status;
  14. char const *queuename;
  15. amqp_socket_t *socket = NULL;
  16. amqp_connection_state_t conn;
  17. if (argc < 4) {
  18. fprintf(stderr, "Usage: amqp_listenq host port queuename\n");
  19. return 1;
  20. }
  21. hostname = argv[1];
  22. port = atoi(argv[2]);
  23. queuename = argv[3];
  24. conn = amqp_new_connection();
  25. socket = amqp_tcp_socket_new(conn);
  26. if (!socket) {
  27. die("creating TCP socket");
  28. }
  29. status = amqp_socket_open(socket, hostname, port);
  30. if (status) {
  31. die("opening TCP socket");
  32. }
  33. die_on_amqp_error(amqp_login(conn, "/", 0, 131072, 0, AMQP_SASL_METHOD_PLAIN,
  34. "guest", "guest"),
  35. "Logging in");
  36. amqp_channel_open(conn, 1);
  37. die_on_amqp_error(amqp_get_rpc_reply(conn), "Opening channel");
  38. amqp_basic_consume(conn, 1, amqp_cstring_bytes(queuename), amqp_empty_bytes,
  39. 0, 0, 0, amqp_empty_table);
  40. die_on_amqp_error(amqp_get_rpc_reply(conn), "Consuming");
  41. for (;;) {
  42. amqp_rpc_reply_t res;
  43. amqp_envelope_t envelope;
  44. amqp_maybe_release_buffers(conn);
  45. res = amqp_consume_message(conn, &envelope, NULL, 0);
  46. if (AMQP_RESPONSE_NORMAL != res.reply_type) {
  47. break;
  48. }
  49. printf("Delivery %u, exchange %.*s routingkey %.*s\n",
  50. (unsigned)envelope.delivery_tag, (int)envelope.exchange.len,
  51. (char *)envelope.exchange.bytes, (int)envelope.routing_key.len,
  52. (char *)envelope.routing_key.bytes);
  53. if (envelope.message.properties._flags & AMQP_BASIC_CONTENT_TYPE_FLAG) {
  54. printf("Content-type: %.*s\n",
  55. (int)envelope.message.properties.content_type.len,
  56. (char *)envelope.message.properties.content_type.bytes);
  57. }
  58. printf("----\n");
  59. amqp_dump(envelope.message.body.bytes, envelope.message.body.len);
  60. amqp_destroy_envelope(&envelope);
  61. }
  62. die_on_amqp_error(amqp_channel_close(conn, 1, AMQP_REPLY_SUCCESS),
  63. "Closing channel");
  64. die_on_amqp_error(amqp_connection_close(conn, AMQP_REPLY_SUCCESS),
  65. "Closing connection");
  66. die_on_error(amqp_destroy_connection(conn), "Ending connection");
  67. return 0;
  68. }