nanomsg_pubsub.cpp
Go to the documentation of this file.
1 
4 /*****************************************************************************
5 ** Includes
6 *****************************************************************************/
7 
8 #include <assert.h>
9 #include <cstdio>
10 #include <ctime>
11 #include <cstring>
12 #include <unistd.h>
13 #include <nanomsg/nn.h>
14 #include <nanomsg/pubsub.h>
15 #include <iostream>
16 
17 #define SERVER "server"
18 #define CLIENT "client"
19 #define URL "ipc:
20 
21 char *date ()
22 {
23  time_t raw = time (&raw);
24  struct tm *info = localtime (&raw);
25  char *text = asctime (info);
26  text[strlen(text)-1] = '\0'; // remove '\n'
27  return text;
28 }
29 
30 int server ()
31 {
32  int sock = nn_socket (AF_SP, NN_PUB);
33  assert (sock >= 0);
34  int result;
35  result = nn_bind (sock, URL);
36  assert (result >= 0);
37  std::cout << "Asserted bind on " << URL << std::endl;
38  while (1)
39  {
40  char *d = date();
41  int sz_d = strlen(d) + 1; // '\0' too
42  printf ("SERVER: PUBLISHING DATE %s\n", d);
43  int bytes = nn_send (sock, d, sz_d, 0);
44  assert (bytes == sz_d);
45  sleep(1);
46  }
47  return nn_shutdown (sock, 0);
48 }
49 
50 int client ()
51 {
52  int sock = nn_socket (AF_SP, NN_SUB);
53  std::cout << "Socket: " << sock << std::endl;
54  assert (sock >= 0);
55  // TODO learn more about publishing/subscribe keys
56  int result;
57  result = nn_setsockopt (sock, NN_SUB, NN_SUB_SUBSCRIBE, "", 0);
58  assert(result >= 0);
59  std::cout << "Asserted nn_setsockopt" << std::endl;
60  result = nn_connect (sock, URL);
61  assert (result >= 0);
62  std::cout << "Asserted nn_connect on " << URL << std::endl;
63  std::cout << "Receiving"<< std::endl;
64  while (1)
65  {
66  char *buf = NULL;
67  int bytes = nn_recv (sock, &buf, NN_MSG, 0);
68  assert (bytes >= 0);
69  printf ("CLIENT: RECEIVED %s\n", buf);
70  nn_freemsg (buf);
71  }
72  return nn_shutdown (sock, 0);
73 }
74 
75 int main (const int argc, const char **argv)
76 {
77  if (argc != 2) {
78  fprintf (stderr, "Usage: pubsub %s|%s \n", SERVER, CLIENT);
79  return 1;
80  }
81  if (strncmp(SERVER, argv[1], strlen(SERVER)) == 0)
82  return server();
83  else if (strncmp (CLIENT, argv[1], strlen (CLIENT)) == 0)
84  return client();
85 }
#define SERVER
char * date()
#define URL
int server()
void d()
int main(const int argc, const char **argv)
int client()
#define CLIENT


mm_mux_demux
Author(s): Daniel Stonier
autogenerated on Mon Jun 10 2019 13:52:14