Go to the documentation of this file.00001
00004
00005
00006
00007
00008 #include <assert.h>
00009 #include <cstdio>
00010 #include <ctime>
00011 #include <cstring>
00012 #include <unistd.h>
00013 #include <nanomsg/nn.h>
00014 #include <nanomsg/pubsub.h>
00015 #include <iostream>
00016
00017 #define SERVER "server"
00018 #define CLIENT "client"
00019 #define URL "ipc:///tmp/nanomsg_pubsub.ipc"
00020
00021 char *date ()
00022 {
00023 time_t raw = time (&raw);
00024 struct tm *info = localtime (&raw);
00025 char *text = asctime (info);
00026 text[strlen(text)-1] = '\0';
00027 return text;
00028 }
00029
00030 int server ()
00031 {
00032 int sock = nn_socket (AF_SP, NN_PUB);
00033 assert (sock >= 0);
00034 int result;
00035 result = nn_bind (sock, URL);
00036 assert (result >= 0);
00037 std::cout << "Asserted bind on " << URL << std::endl;
00038 while (1)
00039 {
00040 char *d = date();
00041 int sz_d = strlen(d) + 1;
00042 printf ("SERVER: PUBLISHING DATE %s\n", d);
00043 int bytes = nn_send (sock, d, sz_d, 0);
00044 assert (bytes == sz_d);
00045 sleep(1);
00046 }
00047 return nn_shutdown (sock, 0);
00048 }
00049
00050 int client ()
00051 {
00052 int sock = nn_socket (AF_SP, NN_SUB);
00053 std::cout << "Socket: " << sock << std::endl;
00054 assert (sock >= 0);
00055
00056 int result;
00057 result = nn_setsockopt (sock, NN_SUB, NN_SUB_SUBSCRIBE, "", 0);
00058 assert(result >= 0);
00059 std::cout << "Asserted nn_setsockopt" << std::endl;
00060 result = nn_connect (sock, URL);
00061 assert (result >= 0);
00062 std::cout << "Asserted nn_connect on " << URL << std::endl;
00063 std::cout << "Receiving"<< std::endl;
00064 while (1)
00065 {
00066 char *buf = NULL;
00067 int bytes = nn_recv (sock, &buf, NN_MSG, 0);
00068 assert (bytes >= 0);
00069 printf ("CLIENT: RECEIVED %s\n", buf);
00070 nn_freemsg (buf);
00071 }
00072 return nn_shutdown (sock, 0);
00073 }
00074
00075 int main (const int argc, const char **argv)
00076 {
00077 if (argc != 2) {
00078 fprintf (stderr, "Usage: pubsub %s|%s \n", SERVER, CLIENT);
00079 return 1;
00080 }
00081 if (strncmp(SERVER, argv[1], strlen(SERVER)) == 0)
00082 return server();
00083 else if (strncmp (CLIENT, argv[1], strlen (CLIENT)) == 0)
00084 return client();
00085 }