Package org.zeromq

Examples of org.zeromq.ZContext


    /**
     * And the main task now sets-up child tasks, then starts its reactor.
     * If you press Ctrl-C, the reactor exits and the main task shuts down.
     */
    public static void main (String[] args) {
        ZContext context = new ZContext();
        LBBroker arg = new LBBroker ();
        //  Prepare our context and sockets
        arg.frontend  = context.createSocket (ZMQ.ROUTER);
        arg.backend  = context.createSocket (ZMQ.ROUTER);
        arg.frontend.bind("ipc://frontend.ipc");
        arg.backend.bind("ipc://backend.ipc");

        int clientNbr;
        for (clientNbr = 0; clientNbr < NBR_CLIENTS; clientNbr++)
            ZThread.start (new ClientTask ());

        for (int workerNbr = 0; workerNbr < NBR_WORKERS; workerNbr++)
            ZThread.start (new WorkerTask ());

        //  Queue of available workers
        arg.workers = new LinkedList<ZFrame> ();

        //  Prepare reactor and fire it up
        ZLoop reactor = new ZLoop ();
        PollItem item = new PollItem (arg.backend, ZMQ.Poller.POLLIN);
        reactor.addPoller (item, backendHandler, arg);
        reactor.start ();

        context.destroy ();
    }
View Full Code Here


    private static class ClientTask implements ZThread.IDetachedRunnable
    {
        @Override
        public void run (Object ... args)
        {
            ZContext context = new ZContext();

            //  Prepare our context and sockets
            Socket client  = context.createSocket (ZMQ.REQ);
            ZHelper.setId (client);     //  Set a printable identity

            client.connect("ipc://frontend.ipc");

            //  Send request, get reply
            client.send("HELLO");
            String reply = client.recvStr ();
            System.out.println("Client: " + reply);

            context.destroy ();
        }
View Full Code Here

    private static class WorkerTask implements ZThread.IDetachedRunnable
    {
        @Override
        public void run (Object ... args)
        {
            ZContext context = new ZContext();

            //  Prepare our context and sockets
            Socket worker  = context.createSocket (ZMQ.REQ);
            ZHelper.setId (worker);     //  Set a printable identity

            worker.connect("ipc://backend.ipc");

            //  Tell backend we're ready for work
            ZFrame frame = new ZFrame (WORKER_READY);
            frame.send (worker, 0);

            while(true)
            {
                ZMsg msg = ZMsg.recvMsg (worker);
                if (msg == null)
                    break;

                msg.getLast ().reset ("OK");
                msg.send (worker);
            }
            context.destroy ();
        }
View Full Code Here

    //  handles subtrees.
    private final static String SUBTREE  = "/client/";


  public void run() {
    ZContext ctx = new ZContext();
    Socket snapshot = ctx.createSocket(ZMQ.DEALER);
    snapshot.connect("tcp://localhost:5556");

    Socket subscriber = ctx.createSocket(ZMQ.SUB);
        subscriber.connect("tcp://localhost:5557");
        subscriber.subscribe(SUBTREE.getBytes());

    Socket publisher = ctx.createSocket(ZMQ.PUSH);
    publisher.connect("tcp://localhost:5558");

        Map<String, kvmsg> kvMap = new HashMap<String, kvmsg>();

        // get state snapshot
    snapshot.sendMore("ICANHAZ?");
        snapshot.send(SUBTREE);
        long sequence = 0;

        while (true) {
            kvmsg kvMsg = kvmsg.recv(snapshot);
            if (kvMsg == null)
                break;      //  Interrupted

      sequence = kvMsg.getSequence();
      if ("KTHXBAI".equalsIgnoreCase(kvMsg.getKey())) {
        System.out.println("Received snapshot = " + kvMsg.getSequence());
                kvMsg.destroy();
        break; // done
      }

            kvMsg.dump();
      System.out.println("receiving " + kvMsg.getSequence());
            kvMsg.store(kvMap);
    }

    Poller poller = new Poller(1);
    poller.register(subscriber);

    Random random = new Random();

    // now apply pending updates, discard out-of-getSequence messages
    long alarm = System.currentTimeMillis() + 5000;
    while (true) {
      int rc = poller.poll(Math.max(0, alarm - System.currentTimeMillis()));
            if (rc == -1)
                break;              //  Context has been shut down

      if (poller.pollin(0)) {
                kvmsg kvMsg = kvmsg.recv(subscriber);
                if (kvMsg == null)
                    break;      //  Interrupted

                if (kvMsg.getSequence() > sequence) {
                    sequence = kvMsg.getSequence();
                    System.out.println("receiving " + sequence);
                    kvMsg.store(kvMap);
                } else
                    kvMsg.destroy();
      }

      if (System.currentTimeMillis() >= alarm) {
        kvmsg kvMsg = new kvmsg(0);
                kvMsg.fmtKey("%s%d", SUBTREE, random.nextInt(10000));
                kvMsg.fmtBody("%d", random.nextInt(1000000));
                kvMsg.setProp("ttl", "%d", random.nextInt(30));
                kvMsg.send(publisher);
                kvMsg.destroy();

        alarm = System.currentTimeMillis() + 1000;
      }
    }
        ctx.destroy();
  }
View Full Code Here

  @Test(timeout = 60000)
  public void exposesZeroMQServer() throws InterruptedException {
    final int port = SocketUtils.findAvailableTcpPort();
    final CountDownLatch latch = new CountDownLatch(2);
    ZContext zmq = new ZContext();

    NetServer<Buffer, Buffer> server = new TcpServerSpec<Buffer, Buffer>(ZeroMQTcpServer.class)
        .env(env)
        .listen(port)
        .consume(ch -> {
          ch.consume(buff -> {
            if (buff.remaining() == 128) {
              latch.countDown();
            } else {
              log.info("data: {}", buff.asString());
            }
            ch.sendAndForget(Buffer.wrap("Goodbye World!"));
          });
        })
        .get();

    assertTrue("Server was started", server.start().await(5, TimeUnit.SECONDS));

    ZeroMQWriter zmqw = new ZeroMQWriter(zmq, port, latch);
    threadPool.submit(zmqw);

    assertTrue("reply was received", latch.await(5, TimeUnit.SECONDS));
    assertTrue("Server was stopped", server.shutdown().await(5, TimeUnit.SECONDS));

    zmq.destroy();
  }
View Full Code Here

  public TcpServer<IN, OUT> start(@Nullable final Runnable started) {
    Assert.isNull(worker, "This ZeroMQ server has already been started");

    UUID id = UUIDUtils.random();
    int socketType = (null != zmqOpts ? zmqOpts.socketType() : ZMQ.ROUTER);
    ZContext zmq = (null != zmqOpts ? zmqOpts.context() : null);
    this.worker = new ZeroMQWorker<IN, OUT>(id, socketType, ioThreadCount, zmq) {
      @Override
      protected void configure(ZMQ.Socket socket) {
        socket.setReceiveBufferSize(getOptions().rcvbuf());
        socket.setSendBufferSize(getOptions().sndbuf());
View Full Code Here

  private void doOpen(final Consumer<NetChannel<IN, OUT>> consumer) {
    final UUID id = UUIDUtils.random();

    int socketType = (null != zmqOpts ? zmqOpts.socketType() : ZMQ.DEALER);
    ZContext zmq = (null != zmqOpts ? zmqOpts.context() : null);

    ZeroMQWorker<IN, OUT> worker = new ZeroMQWorker<IN, OUT>(id, socketType, ioThreadCount, zmq) {
      @Override
      protected void configure(ZMQ.Socket socket) {
        socket.setReceiveBufferSize(getOptions().rcvbuf());
View Full Code Here

  public ZeroMQ(Environment env, Dispatcher dispatcher) {
    this.env = env;
    this.dispatcher = dispatcher;
    this.reactor = Reactors.reactor(env, dispatcher);
    this.zmqCtx = new ZContext();
    this.zmqCtx.setLinger(100);
  }
View Full Code Here

public class tripping {

    static class Broker implements Runnable {
        @Override
        public void run() {
            ZContext ctx = new ZContext();
            Socket frontend = ctx.createSocket(ZMQ.ROUTER);
            Socket backend = ctx.createSocket(ZMQ.ROUTER);
            frontend.bind("tcp://*:5555");
            backend.bind("tcp://*:5556");

            while (!Thread.currentThread().isInterrupted()) {
                ZMQ.Poller items = ctx.getContext().poller();
                items.register(frontend, ZMQ.Poller.POLLIN);
                items.register(backend, ZMQ.Poller.POLLIN);
                if (items.poll() == -1)
                    break; // Interrupted
                if (items.pollin(0)) {
                    ZMsg msg = ZMsg.recvMsg(frontend);
                    if (msg == null)
                        break; // Interrupted
                    ZFrame address = msg.pop();
                    address.destroy();
                    msg.addFirst(new ZFrame("W"));
                    msg.send(backend);
                }
                if (items.pollin(1)) {
                    ZMsg msg = ZMsg.recvMsg(backend);
                    if (msg == null)
                        break; // Interrupted
                    ZFrame address = msg.pop();
                    address.destroy();
                    msg.addFirst(new ZFrame("C"));
                    msg.send(frontend);
                }
            }
            ctx.destroy();
        }
View Full Code Here

    static class Worker implements Runnable {

        @Override
        public void run() {
            ZContext ctx = new ZContext();
            Socket worker = ctx.createSocket(ZMQ.DEALER);
            worker.setIdentity("W".getBytes());
            worker.connect("tcp://localhost:5556");
            while (!Thread.currentThread().isInterrupted()) {
                ZMsg msg = ZMsg.recvMsg(worker);
                msg.send(worker);
            }

            ctx.destroy();

        }
View Full Code Here

TOP

Related Classes of org.zeromq.ZContext

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.