Package org.zeromq

Examples of org.zeromq.ZContext


    private final static String WORKER_READY = "\001";      //  Signals worker is ready

    public static void main(String[] args) throws Exception
    {
        ZContext ctx = new ZContext();
        Socket worker = ctx.createSocket(ZMQ.REQ);

        //  Set random identity to make tracing easier
        Random rand = new Random(System.nanoTime());
        String identity = String.format("%04X-%04X", rand.nextInt(0x10000), rand.nextInt(0x10000));
        worker.setIdentity(identity.getBytes());
        worker.connect("tcp://localhost:5556");

        //  Tell broker we're ready for work
        System.out.printf("I: (%s) worker ready\n", identity);
        ZFrame frame = new ZFrame(WORKER_READY);
        frame.send(worker, 0);

        int cycles = 0;
        while (true) {
            ZMsg msg = ZMsg.recvMsg(worker);
            if (msg == null)
                break;              //  Interrupted

            //  Simulate various problems, after a few cycles
            cycles++;
            if (cycles > 3 && rand.nextInt(5) == 0) {
                System.out.printf("I: (%s) simulating a crash\n", identity);
                msg.destroy();
                break;
            } else if (cycles > 3 && rand.nextInt(5) == 0) {
                System.out.printf("I: (%s) simulating CPU overload\n", identity);
                Thread.sleep(3000);
            }
            System.out.printf("I: (%s) normal reply\n", identity);
            Thread.sleep(1000); //  Do some heavy work
            msg.send(worker);
        }
        ctx.destroy();
    }
View Full Code Here


    //The main thread simply starts several clients, and a server, and then
    //waits for the server to finish.

    public static void main(String[] args) throws Exception {
        ZContext ctx = new ZContext();
        new Thread(new client_task()).start();
        new Thread(new client_task()).start();
        new Thread(new client_task()).start();
        new Thread(new server_task()).start();

        //  Run for 5 seconds then quit
        Thread.sleep(5 * 1000);
        ctx.destroy();
    }
View Full Code Here

    private static Random rand = new Random(System.nanoTime());

    private static class client_task implements Runnable {

        public void run() {
            ZContext ctx = new ZContext();
            Socket client = ctx.createSocket(ZMQ.DEALER);

            //  Set random identity to make tracing easier
            String identity = String.format("%04X-%04X", rand.nextInt(), rand.nextInt());
            client.setIdentity(identity.getBytes());
            client.connect("tcp://localhost:5570");

            PollItem[] items = new PollItem[] { new PollItem(client, Poller.POLLIN) };

            int requestNbr = 0;
            while (!Thread.currentThread().isInterrupted()) {
                //  Tick once per second, pulling in arriving messages
                for (int centitick = 0; centitick < 100; centitick++) {
                    ZMQ.poll(items, 10);
                    if (items[0].isReadable()) {
                        ZMsg msg = ZMsg.recvMsg(client);
                        msg.getLast().print(identity);
                        msg.destroy();
                    }
                }
                client.send(String.format("request #%d", ++requestNbr), 0);
            }
            ctx.destroy();
        }
View Full Code Here

    //one request at a time but one client can talk to multiple workers at
    //once.

    private static class server_task implements Runnable {
        public void run() {
            ZContext ctx = new ZContext();

            //  Frontend socket talks to clients over TCP
            Socket frontend = ctx.createSocket(ZMQ.ROUTER);
            frontend.bind("tcp://*:5570");

            //  Backend socket talks to workers over inproc
            Socket backend = ctx.createSocket(ZMQ.DEALER);
            backend.bind("inproc://backend");

            //  Launch pool of worker threads, precise number is not critical
            for (int threadNbr = 0; threadNbr < 5; threadNbr++)
                new Thread(new server_worker(ctx)).start();

            //  Connect backend to frontend via a proxy
            ZMQ.proxy(frontend, backend, null);

            ctx.destroy();
        }
View Full Code Here

    public static void main(String[] argv) {
        //  Arguments can be either of:
        //      -p  primary server, at tcp://localhost:5001
        //      -b  backup server, at tcp://localhost:5002
        ZContext ctx = new ZContext();
        Socket statepub = ctx.createSocket(ZMQ.PUB);
        Socket statesub = ctx.createSocket(ZMQ.SUB);
        statesub.subscribe("".getBytes());
        Socket frontend = ctx.createSocket(ZMQ.ROUTER);
        bstarsrv fsm = new bstarsrv();

        if (argv.length == 1 && argv[0].equals("-p")) {
            System.out.printf("I: Primary active, waiting for backup (passive)\n");
            frontend.bind("tcp://*:5001");
            statepub.bind("tcp://*:5003");
            statesub.connect("tcp://localhost:5004");
            fsm.state = State.STATE_PRIMARY;
        }
        else
        if (argv.length == 1 && argv[0].equals("-b")) {
            System.out.printf("I: Backup passive, waiting for primary (active)\n");
            frontend.bind("tcp://*:5002");
            statepub.bind("tcp://*:5004");
            statesub.connect("tcp://localhost:5003");
            fsm.state = State.STATE_BACKUP;
        }
        else {
            System.out.printf("Usage: bstarsrv { -p | -b }\n");
            ctx.destroy();
            System.exit(0);
        }
        //  .split handling socket input
        //  We now process events on our two input sockets, and process these
        //  events one at a time via our finite-state machine. Our "work" for
        //  a client request is simply to echo it back:

        //  Set timer for next outgoing state message
        long sendStateAt = System.currentTimeMillis() + HEARTBEAT;
        while (!Thread.currentThread().isInterrupted()) {
            PollItem[] items = {
                    new PollItem(frontend, ZMQ.Poller.POLLIN),
                    new PollItem(statesub, ZMQ.Poller.POLLIN),
            };
            int timeLeft = (int) ((sendStateAt - System.currentTimeMillis()));
            if (timeLeft < 0)
                timeLeft = 0;
            int rc = ZMQ.poll(items, 2, timeLeft);
            if (rc == -1)
                break;              //  Context has been shut down

            if (items[0].isReadable()) {
                //  Have a client request
                ZMsg msg = ZMsg.recvMsg(frontend);
                fsm.event = Event.CLIENT_REQUEST;
                if (fsm.stateMachine() == false)
                    //  Answer client by echoing request back
                    msg.send(frontend);
                else
                    msg.destroy();
            }
            if (items[1].isReadable()) {
                //  Have state from our peer, execute as event
                String message = statesub.recvStr();
                fsm.event = Event.values()[Integer.parseInt(message)];
                if (fsm.stateMachine())
                    break;          //  Error, so exit
                fsm.peerExpiry = System.currentTimeMillis() + 2 * HEARTBEAT;
            }
            //  If we timed out, send state to peer
            if (System.currentTimeMillis() >= sendStateAt) {
                statepub.send(String.valueOf(fsm.state.ordinal()));
                sendStateAt = System.currentTimeMillis() + HEARTBEAT;
            }
        }
        if (Thread.currentThread().isInterrupted())
            System.out.printf ("W: interrupted\n");

        //  Shutdown sockets and context
        ctx.destroy();
    }
View Full Code Here

//
public class spqueue {

    private final static String WORKER_READY  = "\001";      //  Signals worker is ready
    public static void main(String[] args) {
        ZContext ctx = new ZContext ();
        Socket frontend = ctx.createSocket(ZMQ.ROUTER);
        Socket backend = ctx.createSocket(ZMQ.ROUTER);
        frontend.bind("tcp://*:5555");    //  For clients
        backend.bind("tcp://*:5556");    //  For workers

        //  Queue of available workers
        ArrayList<ZFrame> workers = new ArrayList<ZFrame> ();
       
        //  The body of this example is exactly the same as lruqueue2.
        while (true) {
            PollItem items [] = {
                new PollItem( backend,  Poller.POLLIN ),
                new PollItem( frontend, Poller.POLLIN )
            };
            int rc = ZMQ.poll (items, workers.size() > 0 ? 2 : 1, -1);

            //  Poll frontend only if we have available workers
            if (rc == -1)
                break;              //  Interrupted

            //  Handle worker activity on backend
            if (items [0].isReadable()) {
                //  Use worker address for LRU routing
                ZMsg msg = ZMsg.recvMsg(backend);
                if (msg == null)
                    break;          //  Interrupted
                ZFrame address = msg.unwrap();
                workers.add( address);

                //  Forward message to client if it's not a READY
                ZFrame frame = msg.getFirst();
                if (new String(frame.getData()).equals(WORKER_READY))
                    msg.destroy();
                else
                    msg.send(frontend);
            }
            if (items [1].isReadable()) {
                //  Get client request, route to first available worker
                ZMsg msg = ZMsg.recvMsg (frontend);
                if (msg != null) {
                    msg.wrap (workers.remove(0));
                    msg.send(backend);
                }
            }
        }
        //  When we're done, clean up properly
        while (workers.size()>0) {
            ZFrame frame = workers.remove(0);
            frame.destroy();
        }
        workers.clear();
        ctx.destroy();
    }
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

        //  Primary server will become first active
        if (primary)
            kvmap = new HashMap<String, kvmsg>();

        ctx = new ZContext();
        pending = new ArrayList<kvmsg>();
        bStar.setVerbose(true);

        //  Set up our clone server sockets
        publisher = ctx.createSocket(ZMQ.PUB);
View Full Code Here

    public static void main(String[] args)
    {
        boolean verbose = (args.length > 0 && "-v".equals(args[0]));

        ZContext ctx = new ZContext();

        Socket requestPipe = ZThread.fork(ctx, new TitanicRequest());
        ZThread.start(new TitanicReply());
        ZThread.start(new TitanicClose());
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.