View Javadoc
1   package org.sim0mq.test;
2   
3   import java.util.Arrays;
4   
5   import org.sim0mq.Sim0MQException;
6   import org.zeromq.SocketType;
7   import org.zeromq.ZContext;
8   import org.zeromq.ZMQ;
9   
10  /**
11   * Client example for JeroMQ / ZeroMQ.
12   * <p>
13   * (c) copyright 2015-2020 <a href="http://www.simulation.tudelft.nl">Delft University of Technology</a>. <br>
14   * BSD-style license. See <a href="http://www.simulation.tudelft.nl/dsol/3.0/license.html">DSOL License</a>. <br>
15   * @author <a href="http://www.tbm.tudelft.nl/averbraeck">Alexander Verbraeck</a>
16   * @version Oct 21, 2016
17   */
18  public final class TicPush
19  {
20      /** */
21      private TicPush()
22      {
23          // Utility Class.
24      }
25      
26      /**
27       * @param args command line arguments
28       * @throws Sim0MQException on error
29       */
30      public static void main(final String[] args) throws Sim0MQException
31      {
32          long time = System.currentTimeMillis();
33          try (ZContext context = new ZContext(1))
34          {
35              // Socket to talk to server
36              System.out.println("Connecting to server on port 5556...");
37  
38              ZMQ.Socket requester = context.createSocket(SocketType.REQ);
39              requester.connect("tcp://localhost:5556");
40  
41              for (int i = 0; i < 100000; i++)
42              {
43                  // send a request
44                  byte[] message = string2byte("TIC");
45                  requester.send(message, 0);
46  
47                  // wait for reply
48                  byte[] reply = requester.recv(0);
49                  String rs = byte2string(reply);
50                  if (!rs.equals("TOC"))
51                  {
52                      System.err.println("Answer was not TOC");
53                  }
54              }
55  
56              // send stop
57              byte[] message = string2byte("STOP");
58              requester.send(message, 0);
59  
60              requester.close();
61              context.destroy();
62          }
63          System.out.println("RUNTIME = " + (System.currentTimeMillis() - time) + " ms");
64      }
65  
66      /**
67       * Turn String into byte array with closing zero.
68       * @param s the input string
69       * @return byte array with closing zero byte
70       */
71      public static byte[] string2byte(final String s)
72      {
73          byte[] b = s.getBytes();
74          return Arrays.copyOf(b, b.length + 1);
75      }
76  
77      /**
78       * Turn byte array with closing zero into String.
79       * @param b the byte array with closing zero byte
80       * @return String without closing zero
81       */
82      public static String byte2string(final byte[] b)
83      {
84          return new String(Arrays.copyOf(b, b.length - 1));
85      }
86  
87  }