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