APUE Learning Example Source Code
guowenxue
2019-06-26 157be0b0d4c7d4809cfcafc76235cc18388378c8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <cstdio>
#include <cstdlib>
#include <cstring>
 
#include <mosquittopp.h>
 
class mosquittopp_test : public mosqpp::mosquittopp
{
    public:
        mosquittopp_test(const char *id);
 
        void on_connect(int rc);
        void on_message(const struct mosquitto_message *msg);
};
 
mosquittopp_test::mosquittopp_test(const char *id) : mosqpp::mosquittopp(id)
{
}
 
void mosquittopp_test::on_connect(int rc)
{
    if(rc){
        exit(1);
    }
}
 
void mosquittopp_test::on_message(const struct mosquitto_message *msg)
{
    if(msg->mid != 123){
        printf("Invalid mid (%d)\n", msg->mid);
        exit(1);
    }
    if(msg->qos != 1){
        printf("Invalid qos (%d)\n", msg->qos);
        exit(1);
    }
    if(strcmp(msg->topic, "pub/qos1/receive")){
        printf("Invalid topic (%s)\n", msg->topic);
        exit(1);
    }
    if(strcmp((char *)msg->payload, "message")){
        printf("Invalid payload (%s)\n", (char *)msg->payload);
        exit(1);
    }
    if(msg->payloadlen != 7){
        printf("Invalid payloadlen (%d)\n", msg->payloadlen);
        exit(1);
    }
    if(msg->retain != false){
        printf("Invalid retain (%d)\n", msg->retain);
        exit(1);
    }
 
    exit(0);
}
 
int main(int argc, char *argv[])
{
    struct mosquittopp_test *mosq;
 
    int port = atoi(argv[1]);
 
    mosqpp::lib_init();
 
    mosq = new mosquittopp_test("publish-qos1-test");
    mosq->message_retry_set(3);
 
    mosq->connect("localhost", port, 60);
 
    while(1){
        mosq->loop();
    }
 
    mosqpp::lib_cleanup();
 
    return 1;
}