Search in sources :

Example 36 with Socket

use of org.zeromq.ZMQ.Socket in project jeromq by zeromq.

the class bstar method voter.

//  .split voter method
//  This method registers a client voter socket. Messages received
//  on this socket provide the CLIENT_REQUEST events for the Binary Star
//  FSM and are passed to the provided application handler. We require
//  exactly one voter per {{bstar}} instance:
public int voter(String endpoint, int type, IZLoopHandler handler, Object arg) {
    //  Hold actual handler+arg so we can call this later
    Socket socket = ctx.createSocket(type);
    socket.bind(endpoint);
    voterFn = handler;
    voterArg = arg;
    PollItem poller = new PollItem(socket, ZMQ.Poller.POLLIN);
    return loop.addPoller(poller, VoterReady, this);
}
Also used : PollItem(org.zeromq.ZMQ.PollItem) Socket(org.zeromq.ZMQ.Socket)

Example 37 with Socket

use of org.zeromq.ZMQ.Socket in project jeromq by zeromq.

the class bstarsrv method main.

//  .split main task
//  This is our main task. First we bind/connect our sockets with our
//  peer and make sure we will get state messages correctly. We use
//  three sockets; one to publish state, one to subscribe to state, and
//  one for client requests/replies:
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(ZMQ.SUBSCRIPTION_ALL);
    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.
    Poller poller = ctx.createPoller(2);
    poller.register(frontend, ZMQ.Poller.POLLIN);
    poller.register(statesub, ZMQ.Poller.POLLIN);
    //  Set timer for next outgoing state message
    long sendStateAt = System.currentTimeMillis() + HEARTBEAT;
    while (!Thread.currentThread().isInterrupted()) {
        int timeLeft = (int) ((sendStateAt - System.currentTimeMillis()));
        if (timeLeft < 0)
            timeLeft = 0;
        int rc = poller.poll(timeLeft);
        if (rc == -1)
            //  Context has been shut down
            break;
        if (poller.pollin(0)) {
            //  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 (poller.pollin(1)) {
            //  Have state from our peer, execute as event
            String message = statesub.recvStr();
            fsm.event = Event.values()[Integer.parseInt(message)];
            if (fsm.stateMachine())
                //  Error, so exit
                break;
            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();
}
Also used : ZContext(org.zeromq.ZContext) ZMsg(org.zeromq.ZMsg) Socket(org.zeromq.ZMQ.Socket) Poller(org.zeromq.ZMQ.Poller)

Example 38 with Socket

use of org.zeromq.ZMQ.Socket in project jeromq by zeromq.

the class ZContext method destroy.

/**
     * Destructor.  Call this to gracefully terminate context and close any managed 0MQ sockets
     */
public void destroy() {
    for (Socket socket : sockets) {
        socket.setLinger(linger);
        socket.close();
    }
    sockets.clear();
    // Only terminate context if we are on the main thread
    if (isMain() && context != null) {
        context.term();
    }
    synchronized (this) {
        context = null;
    }
}
Also used : Socket(org.zeromq.ZMQ.Socket)

Example 39 with Socket

use of org.zeromq.ZMQ.Socket in project jeromq by zeromq.

the class ZContext method createSocket.

/**
     * Creates a new managed socket within this ZContext instance.
     * Use this to get automatic management of the socket at shutdown
     * @param type
     *          socket type (see ZMQ static class members)
     * @return
     *          Newly created Socket object
     */
public Socket createSocket(int type) {
    // Create and register socket
    Socket socket = getContext().socket(type);
    sockets.add(socket);
    return socket;
}
Also used : Socket(org.zeromq.ZMQ.Socket)

Example 40 with Socket

use of org.zeromq.ZMQ.Socket in project jeromq by zeromq.

the class ZPoller method add.

// add an item to this poller
protected boolean add(Object socketOrChannel, final ItemHolder holder) {
    if (socketOrChannel == null) {
        Socket socket = holder.socket();
        SelectableChannel ch = holder.item().getRawSocket();
        if (socket == null) {
            // not a socket
            assert (ch != null);
            socketOrChannel = ch;
        }
        if (ch == null) {
            // not a channel
            assert (socket != null);
            socketOrChannel = socket;
        }
    }
    assert (socketOrChannel != null);
    Set<ItemHolder> holders = items.get(socketOrChannel);
    if (holders == null) {
        holders = createContainer(1);
        items.put(socketOrChannel, holders);
    }
    final boolean rc = holders.add(holder);
    if (rc) {
        all.add(holder);
    }
    return rc;
}
Also used : SelectableChannel(java.nio.channels.SelectableChannel) Socket(org.zeromq.ZMQ.Socket)

Aggregations

Socket (org.zeromq.ZMQ.Socket)84 Context (org.zeromq.ZMQ.Context)32 ZContext (org.zeromq.ZContext)30 Test (org.junit.Test)26 Poller (org.zeromq.ZMQ.Poller)20 ZMsg (org.zeromq.ZMsg)14 Random (java.util.Random)13 ZFrame (org.zeromq.ZFrame)13 PollItem (org.zeromq.ZMQ.PollItem)6 ByteBuffer (java.nio.ByteBuffer)4 ArrayList (java.util.ArrayList)4 SelectableChannel (java.nio.channels.SelectableChannel)3 HashMap (java.util.HashMap)3 IOException (java.io.IOException)2 LinkedList (java.util.LinkedList)2 Entry (java.util.Map.Entry)2 Ignore (org.junit.Ignore)2 Actor (org.zeromq.ZActor.Actor)2 BufferedWriter (java.io.BufferedWriter)1 File (java.io.File)1