Search in sources :

Example 1 with ZFrame

use of org.zeromq.ZFrame in project jeromq by zeromq.

the class lbbroker2 method main.

/**
     * This is the main task. This has the identical functionality to
     * the previous lbbroker example but uses higher level classes to start child threads
     * to hold the list of workers, and to read and send messages:
     */
public static void main(String[] args) {
    ZContext context = new ZContext();
    //  Prepare our context and sockets
    Socket frontend = context.createSocket(ZMQ.ROUTER);
    Socket backend = context.createSocket(ZMQ.ROUTER);
    frontend.bind("ipc://frontend.ipc");
    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
    Queue<ZFrame> workerQueue = new LinkedList<ZFrame>();
    while (!Thread.currentThread().isInterrupted()) {
        //  Initialize poll set
        Poller items = context.createPoller(2);
        //  Always poll for worker activity on backend
        items.register(backend, Poller.POLLIN);
        //  Poll front-end only if we have available workers
        if (workerQueue.size() > 0)
            items.register(frontend, Poller.POLLIN);
        if (items.poll() < 0)
            //  Interrupted
            break;
        //  Handle worker activity on backend
        if (items.pollin(0)) {
            ZMsg msg = ZMsg.recvMsg(backend);
            if (msg == null)
                //  Interrupted
                break;
            ZFrame identity = msg.unwrap();
            //  Queue worker address for LRU routing
            workerQueue.add(identity);
            //  Forward message to client if it's not a READY
            ZFrame frame = msg.getFirst();
            if (Arrays.equals(frame.getData(), WORKER_READY))
                msg.destroy();
            else
                msg.send(frontend);
        }
        if (items.pollin(1)) {
            //  Get client request, route to first available worker
            ZMsg msg = ZMsg.recvMsg(frontend);
            if (msg != null) {
                msg.wrap(workerQueue.poll());
                msg.send(backend);
            }
        }
    }
    context.destroy();
}
Also used : ZFrame(org.zeromq.ZFrame) ZContext(org.zeromq.ZContext) ZMsg(org.zeromq.ZMsg) Socket(org.zeromq.ZMQ.Socket) LinkedList(java.util.LinkedList) Poller(org.zeromq.ZMQ.Poller)

Example 2 with ZFrame

use of org.zeromq.ZFrame in project jeromq by zeromq.

the class lruqueue3 method main.

public static void main(String[] args) {
    ZContext context = new ZContext();
    LRUQueueArg arg = new LRUQueueArg();
    //  Prepare our context and sockets
    Socket frontend = context.createSocket(ZMQ.ROUTER);
    Socket backend = context.createSocket(ZMQ.ROUTER);
    arg.frontend = frontend;
    arg.backend = backend;
    frontend.bind("ipc://frontend.ipc");
    backend.bind("ipc://backend.ipc");
    int client_nbr;
    for (client_nbr = 0; client_nbr < 10; client_nbr++) new ClientThread3().start();
    int worker_nbr;
    for (worker_nbr = 0; worker_nbr < 3; worker_nbr++) new WorkerThread3().start();
    //  Queue of available workers
    arg.workers = new LinkedList<ZFrame>();
    //  Prepare reactor and fire it up
    ZLoop reactor = new ZLoop(context);
    reactor.verbose(true);
    PollItem poller = new PollItem(arg.backend, ZMQ.Poller.POLLIN);
    reactor.addPoller(poller, handle_backend, arg);
    reactor.start();
    reactor.destroy();
    for (ZFrame frame : arg.workers) {
        frame.destroy();
    }
    context.destroy();
    System.exit(0);
}
Also used : ZFrame(org.zeromq.ZFrame) PollItem(org.zeromq.ZMQ.PollItem) ZLoop(org.zeromq.ZLoop) ZContext(org.zeromq.ZContext) Socket(org.zeromq.ZMQ.Socket)

Example 3 with ZFrame

use of org.zeromq.ZFrame in project jeromq by zeromq.

the class lvcache method main.

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(ZMQ.SUBSCRIPTION_ALL);
    //  Store last instance of each topic in a cache
    Map<String, String> cache = new HashMap<String, String>();
    Poller poller = context.createPoller(2);
    poller.register(frontend, Poller.POLLIN);
    poller.register(backend, Poller.POLLIN);
    //  if anything:
    while (true) {
        if (poller.poll(1000) == -1)
            //  Interrupted
            break;
        //  Any new topic data we cache and then forward
        if (poller.pollin(0)) {
            String topic = frontend.recvStr();
            String current = frontend.recvStr();
            if (topic == null)
                break;
            cache.put(topic, current);
            backend.sendMore(topic);
            backend.send(current);
        }
        //  When we get a new subscription, we pull data from the cache:
        if (poller.pollin(1)) {
            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, ZMQ.CHARSET);
                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();
}
Also used : ZFrame(org.zeromq.ZFrame) HashMap(java.util.HashMap) ZContext(org.zeromq.ZContext) Socket(org.zeromq.ZMQ.Socket) Poller(org.zeromq.ZMQ.Poller)

Example 4 with ZFrame

use of org.zeromq.ZFrame in project jeromq by zeromq.

the class mdbroker method serviceInternal.

/**
     * Handle internal service according to 8/MMI specification
     */
private void serviceInternal(ZFrame serviceFrame, ZMsg msg) {
    String returnCode = "501";
    if ("mmi.service".equals(serviceFrame.toString())) {
        String name = msg.peekLast().toString();
        returnCode = services.containsKey(name) ? "200" : "400";
    }
    msg.peekLast().reset(returnCode.getBytes(ZMQ.CHARSET));
    // Remove & save client return envelope and insert the
    // protocol header and service name, then rewrap envelope.
    ZFrame client = msg.unwrap();
    msg.addFirst(serviceFrame.duplicate());
    msg.addFirst(MDP.C_CLIENT.newFrame());
    msg.wrap(client);
    msg.send(socket);
}
Also used : ZFrame(org.zeromq.ZFrame)

Example 5 with ZFrame

use of org.zeromq.ZFrame in project jeromq by zeromq.

the class mdcliapi method send.

/**
     * Send request to broker and get reply by hook or crook Takes ownership of
     * request message and destroys it when sent. Returns the reply message or
     * NULL if there was no reply.
     *
     * @param service
     * @param request
     * @return
     */
public ZMsg send(String service, ZMsg request) {
    request.push(new ZFrame(service));
    request.push(MDP.C_CLIENT.newFrame());
    if (verbose) {
        log.format("I: send request to '%s' service: \n", service);
        request.dump(log.out());
    }
    ZMsg reply = null;
    int retriesLeft = retries;
    while (retriesLeft > 0 && !Thread.currentThread().isInterrupted()) {
        request.duplicate().send(client);
        // Poll socket for a reply, with timeout
        ZMQ.Poller items = ctx.createPoller(1);
        items.register(client, ZMQ.Poller.POLLIN);
        if (items.poll(timeout) == -1)
            // Interrupted
            break;
        if (items.pollin(0)) {
            ZMsg msg = ZMsg.recvMsg(client);
            if (verbose) {
                log.format("I: received reply: \n");
                msg.dump(log.out());
            }
            // Don't try to handle errors, just assert noisily
            assert (msg.size() >= 3);
            ZFrame header = msg.pop();
            assert (MDP.C_CLIENT.equals(header.toString()));
            header.destroy();
            ZFrame replyService = msg.pop();
            assert (service.equals(replyService.toString()));
            replyService.destroy();
            reply = msg;
            break;
        } else {
            items.unregister(client);
            if (--retriesLeft == 0) {
                log.format("W: permanent error, abandoning\n");
                break;
            }
            log.format("W: no reply, reconnecting\n");
            reconnectToBroker();
        }
    }
    request.destroy();
    return reply;
}
Also used : ZFrame(org.zeromq.ZFrame) ZMsg(org.zeromq.ZMsg) ZMQ(org.zeromq.ZMQ)

Aggregations

ZFrame (org.zeromq.ZFrame)27 ZMsg (org.zeromq.ZMsg)20 ZContext (org.zeromq.ZContext)13 Socket (org.zeromq.ZMQ.Socket)13 Poller (org.zeromq.ZMQ.Poller)7 ArrayList (java.util.ArrayList)4 Random (java.util.Random)4 ZMQ (org.zeromq.ZMQ)4 PollItem (org.zeromq.ZMQ.PollItem)3 IOException (java.io.IOException)2 ZLoop (org.zeromq.ZLoop)2 DataInputStream (java.io.DataInputStream)1 DataOutputStream (java.io.DataOutputStream)1 File (java.io.File)1 FileInputStream (java.io.FileInputStream)1 FileOutputStream (java.io.FileOutputStream)1 RandomAccessFile (java.io.RandomAccessFile)1 HashMap (java.util.HashMap)1 LinkedList (java.util.LinkedList)1