1 /**
2     Nanomsg Example: Pair
3 */
4 module nanomsg.examples.pair;
5 import std.stdio;
6 import core.thread;
7 import std.conv;
8 import nanomsg;
9 
10 ///
11 enum NODE0 ="node0";
12 ///
13 enum NODE1 ="node1";
14 
15 ///
16 int send_name(int sock, string name)
17 {
18   writefln("%s: SENDING \"%s\"\n", name, name);
19   int sz_n = cast(int)name.length+ 1; // '\0' too
20   return nn_send (sock, cast(char*)name, sz_n, 0);
21 }
22 
23 ///
24 int recv_name(int sock, string name)
25 {
26   char *buf = cast(char*)0;
27   int result = nn_recv (sock, &buf, NN_MSG, 0);
28   if (result > 0)
29     {
30       writefln("%s: RECEIVED \"%s\"\n", name, to!string(buf));
31       nn_freemsg (buf);
32     }
33   return result;
34 }
35 
36 ///
37 void send_recv(int sock, string name)
38 {
39   int to = 100;
40   assert (nn_setsockopt (sock, NN_SOL_SOCKET, NN.RCVTIMEO, &to, to.sizeof) >= 0);
41   while(1)
42     {
43       recv_name(sock, name);
44       Thread.sleep( dur!("seconds")( 1 ) );
45       send_name(sock, name);
46     }
47 }
48 
49 ///
50 int node0(string url)
51 {
52   int sock = nn_socket (AF_SP, NN_PAIR);
53   assert (sock >= 0);
54   assert (nn_bind (sock,cast(char*) url) >= 0);
55   send_recv(sock, NODE0);
56   return nn_shutdown (sock, 0);
57 }
58 
59 ///
60 int node1(string url)
61 {
62   int sock = nn_socket (AF_SP, NN_PAIR);
63   assert (sock >= 0);
64   assert (nn_connect (sock, cast(char*)url) >= 0);
65   send_recv(sock, NODE1);
66   return nn_shutdown (sock, 0);
67 }
68 
69 int main(string[] argv)
70 {
71   if (argv.length>1)
72     if (NODE0==argv[1])
73       return node0(argv[2]);
74   if (argv.length>1)
75     if (NODE1==argv[1])
76       return node1(argv[2]);
77   writefln("Usage: pair %s|%s <URL> <ARG> ...",NODE0, NODE1);
78   return 1;
79 }