Package org.zeromq

Examples of org.zeromq.ZContext


    static class Client implements Runnable {
        private static int SAMPLE_SIZE = 10000;

        @Override
        public void run() {
            ZContext ctx = new ZContext();
            Socket client = ctx.createSocket(ZMQ.DEALER);
            client.setIdentity("C".getBytes());
            client.connect("tcp://localhost:5555");
            System.out.println("Setting up test...");
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }

            int requests;
            long start;

            System.out.println("Synchronous round-trip test...");
            start = System.currentTimeMillis();

            for (requests = 0; requests < SAMPLE_SIZE; requests++) {
                ZMsg req = new ZMsg();
                req.addString("hello");
                req.send(client);
                ZMsg.recvMsg(client).destroy();
            }

            System.out.printf(" %d calls/second\n",
                    (1000 * SAMPLE_SIZE) / (System.currentTimeMillis() - start));

            System.out.println("Asynchronous round-trip test...");
            start = System.currentTimeMillis();

            for (requests = 0; requests < SAMPLE_SIZE; requests++) {
                ZMsg req = new ZMsg();
                req.addString("hello");
                req.send(client);
            }
            for (requests = 0; requests < SAMPLE_SIZE
                    && !Thread.currentThread().isInterrupted(); requests++) {
                ZMsg.recvMsg(client).destroy();
            }

            System.out.printf(" %d calls/second\n",
                    (1000 * SAMPLE_SIZE) / (System.currentTimeMillis() - start));

            ctx.destroy();
        }
View Full Code Here


        return true;
    }

    public static void main(String[] args) {
        // Prepare our context and socket
        ZContext context = new ZContext();
        ZMQ.Socket worker = connectWorker(context);

        // If liveness hits zero, queue is considered disconnected
        int liveness = HEARTBEAT_LIVENESS;
        int interval = INTERVAL_INIT;

        // Send out heartbeats at regular intervals
        long heartbeatAt = System.currentTimeMillis() + HEARTBEAT_INTERVAL;

        int cycles = 0;
        while (!Thread.currentThread().isInterrupted()) {

            ZMQ.Poller items = context.getContext().poller();
            items.register(worker, ZMQ.Poller.POLLIN);

            if (items.poll(HEARTBEAT_INTERVAL * 1000) == -1)
                break; // Interrupted

            if (items.pollin(0)) {
                ZMsg msg = ZMsg.recvMsg(worker);
                if (msg == null)
                    break; // Interrupted

                if (msg.size() == 3) { // serving a client request
                    if (!doTheWork(cycles++))
                        break; // crashed
                    liveness = HEARTBEAT_LIVENESS;
                    msg.send(worker);
                } else if (msg.size() == 1) { // heartbeat
                    ZFrame frame = msg.getFirst();
                    if (Arrays.equals(frame.getData(), PPP_HEARTBEAT)) {
                        liveness = HEARTBEAT_LIVENESS;
                    } else {
                        System.out.printf("E: invalid message (%s)\n",
                                frame.toString());
                    }
                    frame.destroy();
                } else {
                    System.out.printf("E: invalid message (%s)\n",
                            msg.toString());
                }
                interval = INTERVAL_INIT;
            } else if (--liveness == 0) {
                System.out.printf("W: heartbeat failure, can't reach queue\n");
                System.out.printf("W: reconnecting in %d msec...\n", interval);
                try {
                    Thread.sleep(interval);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (interval < INTERVAL_MAX)
                    interval *= 2;
                context.destroySocket(worker);
                worker = connectWorker(context);
                liveness = HEARTBEAT_LIVENESS;
            }
            // Send heartbeat to queue if it's time
            if (System.currentTimeMillis() > heartbeatAt) {
                heartbeatAt = System.currentTimeMillis() + HEARTBEAT_INTERVAL;
                System.out.printf("I: worker heartbeat\n");
                heartbeatFrame.sendAndKeep(worker);
            }
        }
        // cleanup
        context.destroy();
    }
View Full Code Here

        this.verbose = verbose;
        this.services = new HashMap<String, Service>();
        this.workers = new HashMap<String, Worker>();
        this.waiting = new ArrayDeque<Worker>();
        this.heartbeatAt = System.currentTimeMillis() + HEARTBEAT_INTERVAL;
        this.ctx = new ZContext();
        this.socket = ctx.createSocket(ZMQ.ROUTER);
    }
View Full Code Here

    }

    public mdcliapi(String broker, boolean verbose) {
        this.broker = broker;
        this.verbose = verbose;
        ctx = new ZContext();
        reconnectToBroker();
    }
View Full Code Here

        assert (broker != null);
        assert (service != null);
        this.broker = broker;
        this.service = service;
        this.verbose = verbose;
        ctx = new ZContext();
        reconnectToBroker();
    }
View Full Code Here

    }

    public mdcliapi2(String broker, boolean verbose) {
        this.broker = broker;
        this.verbose = verbose;
        ctx = new ZContext();
        reconnectToBroker();
    }
View Full Code Here

        }
    }

    public static void main(String[] args) {
        // Prepare our context and sockets
        ZContext context = new ZContext();
        ZMQ.Socket frontend = context.createSocket(ZMQ.ROUTER);
        ZMQ.Socket backend = context.createSocket(ZMQ.ROUTER);
        frontend.bind("tcp://*:5555"); // For clients
        backend.bind("tcp://*:5556"); // For workers
        WorkersPool workers = new WorkersPool();

        while (!Thread.currentThread().isInterrupted()) {
            ZMQ.Poller items = context.getContext().poller();
            items.register(backend, ZMQ.Poller.POLLIN);

            if (!workers.isEmpty()) // poll frontend only if there are
                                    // registered workers
                items.register(frontend, ZMQ.Poller.POLLIN);

            items.poll();
            if (items.pollin(0)) {
                // receive whole message (all ZFrames) at once
                ZMsg msg = ZMsg.recvMsg(backend);
                if (msg == null)
                    break; // Interrupted

                // Any sign of life from worker means it's ready
                ZFrame address = msg.unwrap();
                workers.workerReady(new Worker(address));

                // Validate control message, or return reply to client
                if (msg.size() == 1) {
                    ZFrame frame = msg.getFirst();
                    if (!(Arrays.equals(frame.getData(), PPP_HEARTBEAT) || Arrays
                            .equals(frame.getData(), PPP_READY))) {
                        System.out.printf("E: invalid message from worker "
                                + msg.toString());
                    }
                    msg.destroy();
                } else
                    msg.send(frontend);
            }
            if (items.pollin(1)) {
                // Now get next client request, route to next worker
                ZMsg msg = ZMsg.recvMsg(frontend);
                if (msg == null)
                    break; // Interrupted
                msg.push(workers.next());
                msg.send(backend);
            }

            workers.sendHeartbeats(backend);
            workers.purge();

        }

        // When we're done, clean up properly
        workers.close();
        context.destroy();
    }
View Full Code Here

    @Test
    public void testFmqServer ()
    {

        System.out.printf (" * fmq_server: ");
        ZContext ctx = new ZContext ();
       
        FmqServer self;
        Socket dealer = ctx.createSocket (ZMQ.DEALER);
        dealer.setReceiveTimeOut (2000);
        dealer.connect ("tcp://localhost:5670");
       
        FmqMsg request, reply;
       
        //  Run selftest using '' configuration
        self = new FmqServer ();
        assert (self != null);
        int port = self.bind ("tcp://*:5670");
        assertEquals (port, 5670);           
        request = new FmqMsg (FmqMsg.OHAI);
        request.send (dealer);
        reply = FmqMsg.recv (dealer);
        assert (reply != null);
        assertEquals (reply.id (), FmqMsg.SRSLY);
        reply.destroy ();

        request = new FmqMsg (FmqMsg.ICANHAZ);
        request.send (dealer);
        reply = FmqMsg.recv (dealer);
        assert (reply != null);
        assertEquals (reply.id (), FmqMsg.RTFM);
        reply.destroy ();

        request = new FmqMsg (FmqMsg.NOM);
        request.send (dealer);
        reply = FmqMsg.recv (dealer);
        assert (reply != null);
        assertEquals (reply.id (), FmqMsg.RTFM);
        reply.destroy ();

        request = new FmqMsg (FmqMsg.HUGZ);
        request.send (dealer);
        reply = FmqMsg.recv (dealer);
        assert (reply != null);
        assertEquals (reply.id (), FmqMsg.RTFM);
        reply.destroy ();

        self.destroy ();
        //  Run selftest using 'anonymous.cfg' configuration
        self = new FmqServer ();
        assert (self != null);
        self.configure ("src/test/resources/anonymous.cfg");
        port = self.bind ("tcp://*:5670");
        assertEquals (port, 5670);       
        request = new FmqMsg (FmqMsg.OHAI);
        request.send (dealer);
        reply = FmqMsg.recv (dealer);
        assert (reply != null);
        assertEquals (reply.id (), FmqMsg.OHAI_OK);
        reply.destroy ();

        request = new FmqMsg (FmqMsg.NOM);
        request.send (dealer);

        request = new FmqMsg (FmqMsg.HUGZ);
        request.send (dealer);
        reply = FmqMsg.recv (dealer);
        assert (reply != null);
        assertEquals (reply.id (), FmqMsg.HUGZ_OK);
        reply.destroy ();

        request = new FmqMsg (FmqMsg.YARLY);
        request.send (dealer);
        reply = FmqMsg.recv (dealer);
        assert (reply != null);
        assertEquals (reply.id (), FmqMsg.RTFM);
        reply.destroy ();

        self.destroy ();
        //  Run selftest using 'server_test.cfg' configuration
        self = new FmqServer ();
        assert (self != null);
        self.configure ("src/test/resources/server_test.cfg");
        port = self.bind ("tcp://*:5670");
        assertEquals (port, 5670);       
        request = new FmqMsg (FmqMsg.OHAI);
        request.send (dealer);
        reply = FmqMsg.recv (dealer);
        assert (reply != null);
        assertEquals (reply.id (), FmqMsg.ORLY);
        reply.destroy ();

        request = new FmqMsg (FmqMsg.YARLY);
        request.setMechanism ("PLAIN");                             
        request.setResponse (FmqSasl.plainEncode ("guest", "guest"));
        request.send (dealer);
        reply = FmqMsg.recv (dealer);
        assert (reply != null);
        assertEquals (reply.id (), FmqMsg.OHAI_OK);
        reply.destroy ();

        request = new FmqMsg (FmqMsg.NOM);
        request.send (dealer);

        request = new FmqMsg (FmqMsg.HUGZ);
        request.send (dealer);
        reply = FmqMsg.recv (dealer);
        assert (reply != null);
        assertEquals (reply.id (), FmqMsg.HUGZ_OK);
        reply.destroy ();

        reply = FmqMsg.recv (dealer);
        assert (reply != null);
        assertEquals (reply.id (), FmqMsg.HUGZ);
        reply.destroy ();

        self.destroy ();

        ctx.destroy ();
        //  No clean way to wait for a background thread to exit
        //  Under valgrind this will randomly show as leakage
        //  Reduce this by giving server thread time to exit
        try {Thread.sleep (200);} catch (Exception e) {};
        System.out.printf ("OK\n");
View Full Code Here

        FmqMsg self = new FmqMsg (0);
        assert (self != null);
        self.destroy ();

        //  Create pair of sockets we can send through
        ZContext ctx = new ZContext ();
        assert (ctx != null);

        Socket output = ctx.createSocket (ZMQ.DEALER);
        assert (output != null);
        output.bind ("inproc://selftest");
        Socket input = ctx.createSocket (ZMQ.ROUTER);
        assert (input != null);
        input.connect ("inproc://selftest");
       
        //  Encode/send/decode and verify each message type

        self = new FmqMsg (FmqMsg.OHAI);
        self.send (output);
   
        self = FmqMsg.recv (input);
        assert (self != null);
        self.destroy ();

        self = new FmqMsg (FmqMsg.ORLY);
        self.appendMechanisms ("Name: %s", "Brutus");
        self.appendMechanisms ("Age: %d", 43);
        self.setChallenge (new ZFrame ("Captcha Diem"));
        self.send (output);
   
        self = FmqMsg.recv (input);
        assert (self != null);
        assertEquals (self.mechanisms ().size (), 2);
        assertEquals (self.mechanisms ().get (0), "Name: Brutus");
        assertEquals (self.mechanisms ().get (1), "Age: 43");
        assertTrue (self.challenge ().streq ("Captcha Diem"));
        self.destroy ();

        self = new FmqMsg (FmqMsg.YARLY);
        self.setMechanism ("Life is short but Now lasts for ever");
        self.setResponse (new ZFrame ("Captcha Diem"));
        self.send (output);
   
        self = FmqMsg.recv (input);
        assert (self != null);
        assertEquals (self.mechanism (), "Life is short but Now lasts for ever");
        assertTrue (self.response ().streq ("Captcha Diem"));
        self.destroy ();

        self = new FmqMsg (FmqMsg.OHAI_OK);
        self.send (output);
   
        self = FmqMsg.recv (input);
        assert (self != null);
        self.destroy ();

        self = new FmqMsg (FmqMsg.ICANHAZ);
        self.setPath ("Life is short but Now lasts for ever");
        self.insertOptions ("Name", "Brutus");
        self.insertOptions ("Age", "%d", 43);
        self.insertCache ("Name", "Brutus");
        self.insertCache ("Age", "%d", 43);
        self.send (output);
   
        self = FmqMsg.recv (input);
        assert (self != null);
        assertEquals (self.path (), "Life is short but Now lasts for ever");
        assertEquals (self.options ().size (), 2);
        assertEquals (self.optionsString ("Name", "?"), "Brutus");
        assertEquals (self.optionsNumber ("Age", 0), 43);
        assertEquals (self.cache ().size (), 2);
        assertEquals (self.cacheString ("Name", "?"), "Brutus");
        assertEquals (self.cacheNumber ("Age", 0), 43);
        self.destroy ();

        self = new FmqMsg (FmqMsg.ICANHAZ_OK);
        self.send (output);
   
        self = FmqMsg.recv (input);
        assert (self != null);
        self.destroy ();

        self = new FmqMsg (FmqMsg.NOM);
        self.setCredit ((byte) 123);
        self.setSequence ((byte) 123);
        self.send (output);
   
        self = FmqMsg.recv (input);
        assert (self != null);
        assertEquals (self.credit (), 123);
        assertEquals (self.sequence (), 123);
        self.destroy ();

        self = new FmqMsg (FmqMsg.CHEEZBURGER);
        self.setSequence ((byte) 123);
        self.setOperation ((byte) 123);
        self.setFilename ("Life is short but Now lasts for ever");
        self.setOffset ((byte) 123);
        self.setEof ((byte) 123);
        self.insertHeaders ("Name", "Brutus");
        self.insertHeaders ("Age", "%d", 43);
        self.setChunk (new ZFrame ("Captcha Diem"));
        self.send (output);
   
        self = FmqMsg.recv (input);
        assert (self != null);
        assertEquals (self.sequence (), 123);
        assertEquals (self.operation (), 123);
        assertEquals (self.filename (), "Life is short but Now lasts for ever");
        assertEquals (self.offset (), 123);
        assertEquals (self.eof (), 123);
        assertEquals (self.headers ().size (), 2);
        assertEquals (self.headersString ("Name", "?"), "Brutus");
        assertEquals (self.headersNumber ("Age", 0), 43);
        assertTrue (self.chunk ().streq ("Captcha Diem"));
        self.destroy ();

        self = new FmqMsg (FmqMsg.HUGZ);
        self.send (output);
   
        self = FmqMsg.recv (input);
        assert (self != null);
        self.destroy ();

        self = new FmqMsg (FmqMsg.HUGZ_OK);
        self.send (output);
   
        self = FmqMsg.recv (input);
        assert (self != null);
        self.destroy ();

        self = new FmqMsg (FmqMsg.KTHXBAI);
        self.send (output);
   
        self = FmqMsg.recv (input);
        assert (self != null);
        self.destroy ();

        self = new FmqMsg (FmqMsg.SRSLY);
        self.setReason ("Life is short but Now lasts for ever");
        self.send (output);
   
        self = FmqMsg.recv (input);
        assert (self != null);
        assertEquals (self.reason (), "Life is short but Now lasts for ever");
        self.destroy ();

        self = new FmqMsg (FmqMsg.RTFM);
        self.setReason ("Life is short but Now lasts for ever");
        self.send (output);
   
        self = FmqMsg.recv (input);
        assert (self != null);
        assertEquals (self.reason (), "Life is short but Now lasts for ever");
        self.destroy ();

        ctx.destroy ();
        System.out.printf ("OK\n");
    }
View Full Code Here

    //  --------------------------------------------------------------------------
    //  Create a new FmqClient and a new client instance

    public FmqClient ()
    {
        ctx = new ZContext ();
        pipe = ZThread.fork (ctx, new ClientThread ());
    }
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.