1 /**
2     Nanomsg Example: Survey
3 */
4 module nanomsg.examples.survey;
5 
6 import std.stdio;
7 import std.datetime;
8 import std.conv;
9 import core.thread;
10 import nanomsg;
11 import std.string:toStringz;
12 
13 ///
14 enum SERVER ="server";
15 ///
16 enum CLIENT ="client";
17 ///
18 enum DATE  = "DATE";
19 
20 ///
21 string date ()
22 {
23   return Clock.currTime.toSimpleString();
24 }
25 
26 ///
27 int server (string surl)
28 {
29   auto url=surl.toStringz;
30   int sock = nn_socket (AF_SP, NN_SURVEYOR);
31   assert (sock >= 0);
32   assert (nn_bind (sock, url) >= 0);
33   Thread.sleep( dur!("seconds")( 1 ) ); // wait for connections
34   int sz_d = cast(int)DATE.length+1;
35   writefln("SERVER: SENDING DATE SURVEY REQUEST");
36   int bytes = nn_send (sock, DATE.toStringz, sz_d, 0);
37   assert (bytes == sz_d);
38   while (1)
39     {
40       char *buf = cast(char*)0;
41       int nubytes = nn_recv (sock, &buf, NN_MSG, 0);
42       if (nubytes == ETIMEDOUT) break;
43       if (nubytes >= 0)
44       {
45         writefln("SERVER: RECEIVED \"%s\" SURVEY RESPONSE", to!string(buf));
46         nn_freemsg (buf);
47       }
48     }
49   return nn_shutdown (sock, 0);
50 }
51 
52 ///
53 int client(string surl,string sname)
54 {
55   auto url=surl.toStringz;
56   auto name=sname.toStringz;
57   int sock = nn_socket (AF_SP, NN_RESPONDENT);
58   assert (sock >= 0);
59   assert (nn_connect (sock, url) >= 0);
60   while (1)
61     {
62       char *buf = cast(char*)0;
63       int bytes = nn_recv (sock, &buf, NN_MSG, 0);
64       if (bytes >= 0)
65         {
66           writefln("CLIENT (%s): RECEIVED \"%s\" SURVEY REQUEST", to!string(name), to!string(buf));
67           nn_freemsg (buf);
68           string d = date();
69           int sz_d = cast(int)d.length+1;
70           writefln("CLIENT (%s): SENDING DATE SURVEY RESPONSE", to!string(name));
71           int nubytes = nn_send (sock, d.toStringz, sz_d, 0);
72           assert (nubytes == sz_d);
73         }
74     }
75   return nn_shutdown (sock, 0);
76 }
77 
78 ///
79 int main (string[] argv)
80 {
81   if (argv.length>=2)
82     if (argv[1]==SERVER)
83       return server (argv[2]);
84   if (argv.length>=3)
85     if (argv[1]==CLIENT)
86       return client(argv[2], argv[3]);
87   writefln("Usage: survey %s|%s <URL> <ARG> ...",SERVER, CLIENT);
88   return 1;
89 }