Package org.zeromq

Examples of org.zeromq.ZContext


    private final static int REQUEST_RETRIES = 3;       //  Before we abandon
    private final static String SERVER_ENDPOINT = "tcp://localhost:5555";

    public static void main(String[] argv)
    {
        ZContext ctx = new ZContext();
        System.out.println("I: connecting to server");
        Socket client = ctx.createSocket(ZMQ.REQ);
        assert (client != null);
        client.connect(SERVER_ENDPOINT);

        int sequence = 0;
        int retriesLeft = REQUEST_RETRIES;
        while (retriesLeft > 0 && !Thread.currentThread().isInterrupted()) {
            //  We send a request, then we work to get a reply
            String request = String.format("%d", ++sequence);
            client.send(request);

            int expect_reply = 1;
            while (expect_reply > 0) {
                //  Poll socket for a reply, with timeout
                PollItem items[] = {new PollItem(client, Poller.POLLIN)};
                int rc = ZMQ.poll(items, REQUEST_TIMEOUT);
                if (rc == -1)
                    break;          //  Interrupted

                //  Here we process a server reply and exit our loop if the
                //  reply is valid. If we didn't a reply we close the client
                //  socket and resend the request. We try a number of times
                //  before finally abandoning:

                if (items[0].isReadable()) {
                    //  We got a reply from the server, must match sequence
                    String reply = client.recvStr();
                    if (reply == null)
                        break;      //  Interrupted
                    if (Integer.parseInt(reply) == sequence) {
                        System.out.printf("I: server replied OK (%s)\n", reply);
                        retriesLeft = REQUEST_RETRIES;
                        expect_reply = 0;
                    } else
                        System.out.printf("E: malformed reply from server: %s\n",
                                reply);

                } else if (--retriesLeft == 0) {
                    System.out.println("E: server seems to be offline, abandoning\n");
                    break;
                } else {
                    System.out.println("W: no response from server, retrying\n");
                    //  Old socket is confused; close it and open a new one
                    ctx.destroySocket(client);
                    System.out.println("I: reconnecting to server\n");
                    client = ctx.createSocket(ZMQ.REQ);
                    client.connect(SERVER_ENDPOINT);
                    //  Send request again, on new socket
                    client.send(request);
                }
            }
        }
        ctx.destroy();
    }
View Full Code Here


    }

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

    //  This is the constructor for our {{bstar}} class. We have to tell it
    //  whether we're primary or backup server, as well as our local and
    //  remote endpoints to bind and connect to:
    public bstar(boolean primary, String local, String remote) {
        //  Initialize the Binary Star
        ctx = new ZContext();
        loop = new ZLoop();
        state = primary? State.STATE_PRIMARY: State.STATE_BACKUP;

        //  Create publisher for state going to peer
        statepub = ctx.createSocket(ZMQ.PUB);
View Full Code Here

    private final static String SUBTREE  = "/client/";

  private static Map<String, kvsimple> kvMap = new HashMap<String, kvsimple>();

  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 push = ctx.createSocket(ZMQ.PUSH);
    push.connect("tcp://localhost:5558");

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

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

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

      System.out.println("receiving " + kvMsg.getSequence());
      clonecli4.kvMap.put(kvMsg.getKey(), kvMsg);
    }

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

    Random random = new Random();

    // now apply pending updates, discard out-of-sequence 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)) {
                kvsimple kvMsg = kvsimple.recv(subscriber);
                if (kvMsg == null)
                    break;      //  Interrupted
                if (kvMsg.getSequence() > sequence) {
                    sequence = kvMsg.getSequence();
                    System.out.println("receiving " + sequence);
                    clonecli4.kvMap.put(kvMsg.getKey(), kvMsg);
                }
      }

      if (System.currentTimeMillis() >= alarm) {
        String key = String.format("%s%d", SUBTREE, random.nextInt(10000));
        int body = random.nextInt(1000000);

        ByteBuffer b = ByteBuffer.allocate(4);
        b.asIntBuffer().put(body);

        kvsimple kvUpdateMsg = new kvsimple(key, 0, b.array());
        kvUpdateMsg.send(push);
        alarm = System.currentTimeMillis() + 1000;
      }
    }
        ctx.destroy();
  }
View Full Code Here

//  Uses XPUB subscription messages to re-send data
public class lvcache
{
    public static void main(String[] args)
    {
        ZContext context = new ZContext();
        Socket frontend = context.createSocket(ZMQ.SUB);
        frontend.bind("tcp://*:5557");
        Socket backend = context.createSocket(ZMQ.XPUB);
        backend.bind("tcp://*:5558");

        //  Subscribe to every single topic from publisher
        frontend.subscribe("".getBytes());

        //  Store last instance of each topic in a cache
        Map<String, String> cache = new HashMap<String, String>();

        //  .split main poll loop
        //  We route topic updates from frontend to backend, and
        //  we handle subscriptions by sending whatever we cached,
        //  if anything:
        while (true) {
            PollItem[] items = {
                    new PollItem(frontend, ZMQ.Poller.POLLIN),
                    new PollItem(backend, ZMQ.Poller.POLLIN),
            };
            if (ZMQ.poll(items, 1000) == -1)
                break;              //  Interrupted

            //  Any new topic data we cache and then forward
            if (items[0].isReadable()) {
                String topic = frontend.recvStr();
                String current = frontend.recvStr();

                if (topic == null)
                    break;
                cache.put(topic, current);
                backend.sendMore(topic);
                backend.send(current);
            }
            //  .split handle subscriptions
            //  When we get a new subscription, we pull data from the cache:
            if (items[1].isReadable()) {
                ZFrame frame = ZFrame.recvFrame(backend);
                if (frame == null)
                    break;
                //  Event is one byte 0=unsub or 1=sub, followed by topic
                byte[] event = frame.getData();
                if (event [0] == 1) {
                    String topic = new String(event, 1, event.length -1);
                    System.out.printf ("Sending cached topic %s\n", topic);
                    String previous = cache.get(topic);
                    if (previous != null) {
                        backend.sendMore(topic);
                        backend.send(previous);
                    }
                }
                frame.destroy();
            }
        }
        context.destroy();
    }
View Full Code Here

    };

    //  The main task is an LRU queue with heartbeating on workers so we can
    //  detect crashed or blocked worker tasks:
    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

        //  List of available workers
        ArrayList<Worker> workers = new ArrayList<Worker> ();

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

        while (true) {
            PollItem items [] = {
                new PollItem( backend,  ZMQ.Poller.POLLIN ),
                new PollItem( frontend, ZMQ.Poller.POLLIN )
            };
            //  Poll frontend only if we have available workers
            int rc = ZMQ.poll (items, workers.size() > 0 ? 2:1,
                HEARTBEAT_INTERVAL );
            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

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

                //  Validate control message, or return reply to client
                if (msg.size() == 1) {
                    ZFrame frame = msg.getFirst();
                    String data = new String(frame.getData());
                    if (!data.equals(PPP_READY)
                    &&  !data.equals( PPP_HEARTBEAT)) {
                        System.out.println ("E: invalid message from worker");
                        msg.dump(System.out);
                    }
                    msg.destroy();
                }
                else
                    msg.send(frontend);
            }
            if (items [1].isReadable()) {
                //  Now get next client request, route to next worker
                ZMsg msg = ZMsg.recvMsg (frontend);
                if (msg == null)
                    break;          //  Interrupted
                msg.push(Worker.next(workers));
                msg.send( backend);
            }

            //  We handle heartbeating after any socket activity. First we send
            //  heartbeats to any idle workers if it's time. Then we purge any
            //  dead workers:
           
            if (System.currentTimeMillis() >= heartbeat_at) {
                for (Worker worker: workers) {
                   
                    worker.address.send(backend,
                                 ZFrame.REUSE + ZFrame.MORE);
                    ZFrame frame = new ZFrame (PPP_HEARTBEAT);
                    frame.send(backend, 0);
                }
                heartbeat_at = System.currentTimeMillis() + HEARTBEAT_INTERVAL;
            }
            Worker.purge (workers);
        }

        //  When we're done, clean up properly
        while ( workers.size() > 0) {
            Worker worker = workers.remove(0);
        }
        workers.clear();
        ctx.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 static void main(String[] args)
    {
        boolean verbose = (args.length > 0 && args[0].equals("-v"));

        ZContext ctx = new ZContext();
        //  Prepare server socket with predictable identity
        String bindEndpoint = "tcp://*:5555";
        String connectEndpoint = "tcp://localhost:5555";
        Socket server = ctx.createSocket(ZMQ.ROUTER);
        server.setIdentity(connectEndpoint.getBytes());
        server.bind(bindEndpoint);
        System.out.printf ("I: service is ready at %s\n", bindEndpoint);

        while (!Thread.currentThread().isInterrupted()) {
            ZMsg request = ZMsg.recvMsg(server);
            if (verbose && request != null)
                request.dump(System.out);

            if (request == null)
                break;          //  Interrupted

            //  Frame 0: identity of client
            //  Frame 1: PING, or client control frame
            //  Frame 2: request body
            ZFrame identity = request.pop();
            ZFrame control = request.pop();
            ZMsg reply = new ZMsg();
            if (control.equals("PING"))
                reply.add("PONG");
            else {
                reply.add(control);
                reply.add("OK");
            }
            request.destroy();
            reply.push(identity);
            if (verbose && reply != null)
                reply.dump(System.out);
            reply.send(server);
        }
        if (Thread.currentThread().isInterrupted())
            System.out.printf ("W: interrupted\n");

        ctx.destroy();
    }
View Full Code Here

    //  .split main task
    //  The main task simply starts a client and a server, and then
    //  waits for the client to signal that it has died:
    public static void main (String[] args) throws Exception
    {
        ZContext ctx = new ZContext();
        Socket pubpipe = ZThread.fork(ctx, new Publisher());
        Socket subpipe = ZThread.fork(ctx, new Subscriber());
        subpipe.recvStr();
        pubpipe.send("break");
        Thread.sleep(100);
        ctx.destroy();
    }
View Full Code Here

//  Sends out 1,000 topics and then one random update per second
public class pathopub
{
    public static void main(String[] args) throws Exception
    {
        ZContext context = new ZContext();
        Socket publisher = context.createSocket(ZMQ.PUB);
        if (args.length == 1)
            publisher.connect(args[0]);
        else
            publisher.bind("tcp://*:5556");

        //  Ensure subscriber connection has time to complete
        Thread.sleep(1000);

        //  Send out all 1,000 topic messages
        int topicNbr;
        for (topicNbr = 0; topicNbr < 1000; topicNbr++) {
            publisher.send(String.format("%03d", topicNbr), ZMQ.SNDMORE);
            publisher.send("Save Roger");
        }
        //  Send one random update per second
        Random rand = new Random(System.currentTimeMillis());
        while (!Thread.currentThread().isInterrupted()) {
            Thread.sleep(1000);
            publisher.send(String.format("%03d", rand.nextInt(1000)), ZMQ.SNDMORE);
            publisher.send("Off with his head!");
        }
        context.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.