Debian Codegraph @

cpp/examples/direct_recv.cpp

raw
1 /*
2 *
3 * Licensed to the Apache Software Foundation (ASF) under one
4 * or more contributor license agreements. See the NOTICE file
5 * distributed with this work for additional information
6 * regarding copyright ownership. The ASF licenses this file
7 * to you under the Apache License, Version 2.0 (the
8 * "License"); you may not use this file except in compliance
9 * with the License. You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing,
14 * software distributed under the License is distributed on an
15 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
16 * KIND, either express or implied. See the License for the
17 * specific language governing permissions and limitations
18 * under the License.
19 *
20 */
21
22 #include "options.hpp"
23
24 #include <proton/connection.hpp>
25 #include <proton/container.hpp>
26 #include <proton/delivery.hpp>
27 #include <proton/message.hpp>
28 #include <proton/message_id.hpp>
29 #include <proton/messaging_handler.hpp>
30 #include <proton/link.hpp>
31 #include <proton/listen_handler.hpp>
32 #include <proton/listener.hpp>
33 #include <proton/value.hpp>
34
35 #include <iostream>
36 #include <map>
37
38
39 class direct_recv : public proton::messaging_handler {
40 private:
41 class listener_ready_handler : public proton::listen_handler {
42 void on_open(proton::listener& l) override {
43 std::cout << "listening on " << l.port() << std::endl;
44 }
45 };
46
47 std::string url;
48 proton::listener listener;
49 listener_ready_handler listen_handler;
50 int expected;
51 int received;
52
53 public:
54 direct_recv(const std::string &s, int c) : url(s), expected(c), received(0) {}
55
56 void on_container_start(proton::container &c) override {
57 listener = c.listen(url, listen_handler);
58 }
59
60 void on_message(proton::delivery &d, proton::message &msg) override {
61 if (proton::coerce<int>(msg.id()) < received) {
62 return; // Ignore duplicate
63 }
64
65 if (expected == 0 || received < expected) {
66 std::cout << msg.body() << std::endl;
67 received++;
68 }
69
70 if (received == expected) {
71 d.receiver().close();
72 d.connection().close();
73 listener.stop();
74 }
75 }
76 };
77
78 int main(int argc, char **argv) {
79 std::string address("127.0.0.1:5672/examples");
80 int message_count = 100;
81 example::options opts(argc, argv);
82
83 opts.add_value(address, 'a', "address", "listen and receive on URL", "URL");
84 opts.add_value(message_count, 'm', "messages", "receive COUNT messages", "COUNT");
85
86 try {
87 opts.parse();
88
89 direct_recv recv(address, message_count);
90 proton::container(recv).run();
91
92 return 0;
93 } catch (const example::bad_option& e) {
94 std::cout << opts << std::endl << e.what() << std::endl;
95 } catch (const std::exception& e) {
96 std::cerr << e.what() << std::endl;
97 }
98
99 return 1;
100 }