1 /**
2     Nanomsg Example: Bus
3 */
4 module nanomsg.examples.bus;
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 ///
15 int node (string[] argv)
16 {
17   int sock = nn_socket (AF_SP, NN_BUS);
18   assert (sock >= 0);
19   assert (nn_bind (sock, argv[2].toStringz) >= 0);
20   Thread.sleep( dur!("seconds")( 1 ) ); // wait for connections
21   if (argv.length>=3)
22     {
23       foreach(x; 3..argv.length)
24         assert (nn_connect (sock, argv[x].toStringz) >= 0);
25     }
26   Thread.sleep( dur!("seconds")( 1 ) ); // wait for connections
27   int to = 100;
28   assert (nn_setsockopt (sock, NN_SOL_SOCKET, NN.RCVTIMEO, &to, to.sizeof) >= 0);
29   // SEND
30   int sz_n = cast(int)argv[1].length+1; // '\0' too
31   writefln("%s: SENDING '%s' ONTO BUS", argv[1], argv[2]);
32   int send = nn_send (sock, argv[1].toStringz, sz_n, 0);
33   assert (send == sz_n);
34   while (1)
35     {
36       // RECV
37       char* buf = cast(char*)0;
38       int recv = nn_recv (sock, &buf, NN_MSG, 0);
39       if (recv >= 0)
40         {
41           writefln("%s: RECEIVED '%s' FROM BUS",argv[1],buf.to!string);
42           nn_freemsg (buf);
43         }
44     }
45   return nn_shutdown (sock, 0);
46 }
47 
48 // weird behaviour so broke this out to a function
49 ///
50 string tostring(char* buf)
51 {
52   return to!string(buf);
53 }
54 
55 ///
56 int main (string[] argv)
57 {
58   if (argv.length>= 3) node(argv);
59   else
60     {
61       writefln("Usage: bus <NODE_NAME> <URL> <URL> ...");
62       return 1;
63     }
64   return 0;
65 }