-
Notifications
You must be signed in to change notification settings - Fork 4
/
subscriber.c
68 lines (56 loc) · 1.43 KB
/
subscriber.c
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
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <nanomsg/nn.h>
#include <nanomsg/pubsub.h>
const char *URL = "ipc:///tmp/example7";
void report_error(const char *func)
{
fprintf(stderr, "%s: %s\n", func, nn_strerror(nn_errno()));
exit(1);
}
void receive_message(const int socket)
{
char *message = NULL;
int bytes;
if ((bytes = nn_recv(socket, &message, NN_MSG, 0)) < 0) {
report_error("nn_recv");
}
printf("Received message '%s' with length %d bytes\n", message, bytes);
if (nn_freemsg(message) < 0) {
report_error("nn_freemsg");
}
}
void subscriber(const char *url)
{
int socket;
int endpoint;
int messages;
if ((socket = nn_socket(AF_SP, NN_SUB)) < 0) {
report_error("nn_socket");
}
puts("Socket created");
if (nn_setsockopt(socket, NN_SUB, NN_SUB_SUBSCRIBE, "", 0) < 0) {
report_error("nn_setsockopt");
}
if ((endpoint = nn_connect(socket, url)) < 0) {
report_error("nn_connect");
}
puts("Endpoint connected to socket");
puts("Waiting for messages...");
while (1) {
receive_message(socket);
messages++;
printf("Processed %d messages so far\n", messages);
}
if (nn_shutdown(socket, endpoint) < 0) {
report_error("nn_shutdown");
}
puts("Shutdown completed");
}
int main(int argc, char **argv)
{
subscriber(URL);
return 0;
}