org.zeromq.ZMQ.Socket Java Examples

The following examples show how to use org.zeromq.ZMQ.Socket. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ZFrame.java    From aion with MIT License 6 votes vote down vote up
/**
 * Internal method to call recv on the socket. Does not trap any
 * ZMQExceptions but expects caling routine to handle them.
 * @param socket
 *            0MQ socket to read from
 * @return Byte array
 */
private byte[] recv(Socket socket, int flags)
{
    try {
        data = socket.recv(flags);
        more = socket.hasReceiveMore();
    } catch (ZMQException e) {
        ZMQ.Error error = ZMQ.Error.findByCode(e.getErrorCode());
        if (error == ZMQ.Error.ETERM || error == ZMQ.Error.ENOTSOCK) {
            data = null;
            more = false;
        } else {
            throw e;
        }
    }
    return data;
}
 
Example #2
Source File: ZContext.java    From aion with MIT License 6 votes vote down vote up
/**
 * Destroys managed socket within this context and remove from sockets list
 * 
 * @param s org.zeromq.Socket object to destroy
 */
public void destroySocket(Socket s) {
    if (s == null)
        return;

    if (sockets.contains(s)) {
        try {
            s.setLinger(linger);
        } catch (ZMQException e) {
            if (e.getErrorCode() != ZMQ.ETERM()) {
                throw e;
            }
        }
        s.close();
        sockets.remove(s);
    }
}
 
Example #3
Source File: ZThread.java    From aion with MIT License 6 votes vote down vote up
public static Socket fork(ZContext ctx, IAttachedRunnable runnable, Object... args) {
    Socket pipe = ctx.createSocket(ZMQ.PAIR);

    if (pipe != null) {
        pipe.bind(String.format("inproc://zctx-pipe-%d", pipe.hashCode()));
    } else {
        return null;
    }

    // Connect child pipe to our pipe
    ZContext ccontext = ZContext.shadow(ctx);
    Socket cpipe = ccontext.createSocket(ZMQ.PAIR);
    if (cpipe == null)
        return null;
    cpipe.connect(String.format("inproc://zctx-pipe-%d", pipe.hashCode()));

    // Prepare child thread
    Thread shim = new ShimThread(ccontext, runnable, args, cpipe);
    shim.start();

    return pipe;
}
 
Example #4
Source File: Proxy.java    From aion with MIT License 6 votes vote down vote up
private static boolean msgProcessSend(Socket receiver, Socket sender) {
    byte[] msg = receiver.recv(0);
    if (msg == null) {
        return true;
    }

    byte[] msgMore = null;
    if (receiver.hasReceiveMore()) {
        msgMore = receiver.recv(0);

        if (msgMore == null) {
            return true;
        }
    }

    if (!sender.send(msg, msgMore == null ? ZMQ.DONTWAIT : ZMQ.SNDMORE)) {
        return true;
    }

    if (msgMore != null) {
        return !sender.send(msgMore, ZMQ.DONTWAIT);
    }

    return false;
}
 
Example #5
Source File: MsgExecutor.java    From aion_api with MIT License 6 votes vote down vote up
private void callbackRun(Context ctx) {
    Socket cbWorker = ctx.socket(ZMQ.DEALER);
    cbWorker.setReceiveTimeOut(RECVTIMEOUT);
    cbWorker.connect(CB_BIND_ADDR + addrBindNumber);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("connected!");
    }

    while (true) {
        byte[] rsp = cbWorker.recv(ZMQ.PAIR);
        if (this.running) {
            if (LOGGER.isTraceEnabled()) {
                LOGGER.trace(
                        "recv msg: [{}]", (rsp != null ? IUtils.bytes2Hex(rsp) : "= null"));
            }
            process(rsp);
        } else {
            break;
        }
    }

    LOGGER.info("closing!");
    cbWorker.close();
    LOGGER.info("closed!");
}
 
Example #6
Source File: ZMsg.java    From aion with MIT License 6 votes vote down vote up
/**
 * Receives message from socket, returns ZMsg object or null if the recv was
 * interrupted. Does a blocking recv, if you want not to block then use the
 * ZLoop class or ZMQ.Poller to check for socket input before receiving.
 * @param socket
 * @param flag
 *            see ZMQ constants
 * @return
 */
public static ZMsg recvMsg(Socket socket, int flag)
{
    if (socket == null)
        throw new IllegalArgumentException("socket is null");

    ZMsg msg = new ZMsg();

    while (true) {
        ZFrame f = ZFrame.recvFrame(socket, flag);
        if (f == null || !f.hasData()) {
            // If receive failed or was interrupted
            msg.destroy();
            msg = null;
            break;
        }
        msg.add(f);
        if (!f.hasMore())
            break;
    }
    return msg;
}
 
Example #7
Source File: MsgExecutor.java    From aion_api with MIT License 6 votes vote down vote up
private boolean invalidMsgHandle(Socket receiver, Socket sender) {

        byte[] msg = receiver.recv(ZMQ.PAIR);
        if (msg == null) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("[invalidMsgHandle] {}", ErrId.getErrString(-322L));
            }
            return true;
        }

        if (!sender.send(msg, ZMQ.DONTWAIT)) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("[invalidMsgHandle] {}", ErrId.getErrString(-323L));
            }
            return true;
        }

        return false;
    }
 
Example #8
Source File: ZMsg.java    From aion with MIT License 6 votes vote down vote up
/**
 * Send message to 0MQ socket, destroys contents after sending if destroy
 * param is set to true. If the message has no frames, sends nothing but
 * still destroy()s the ZMsg object
 * @param socket
 *            0MQ socket to send ZMsg on.
 */
public void send(Socket socket, boolean destroy)
{
    if (socket == null)
        throw new IllegalArgumentException("socket is null");
    if (frames.size() == 0)
        return;
    Iterator<ZFrame> i = frames.iterator();
    while (i.hasNext()) {
        ZFrame f = i.next();
        f.send(socket, (i.hasNext()) ? ZMQ.SNDMORE : 0);
    }
    if (destroy) {
        destroy();
    }
}
 
Example #9
Source File: TestAsyncMicroServiceMain.java    From ignite-book-code-samples with GNU General Public License v3.0 6 votes vote down vote up
private static void sendAsync(int val, String account) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    Context context = ZMQ.context(1);

    //  Socket to talk to server
    Socket requester = context.socket(ZMQ.REQ);
    requester.connect("tcp://localhost:5559");
    System.out.println("launch and connect client.");
    ValidateRequest req = new ValidateRequest(account, new BigDecimal(val));

    //send request
    requester.send(objectMapper.writeValueAsString(req), 0);
    //receive response
    String responseStr = requester.recvStr(0);

    //parse and print reply
    ValidateResponse reply = objectMapper.readValue(responseStr, ValidateResponse.class);
    System.out.println("Received reply for request= " + req + " reply= " + reply + "");

    //  We never get here but clean up anyhow
    requester.close();
    context.term();
}
 
Example #10
Source File: ZeroMQBroker.java    From ignite-book-code-samples with GNU General Public License v3.0 6 votes vote down vote up
public static void main (String[] args) {
    //  Prepare our context and sockets
    Context context = ZMQ.context(1);

    //  Socket facing clients
    Socket frontend = context.socket(ZMQ.ROUTER);
    frontend.bind("tcp://*:5559");

    //  Socket facing services
    Socket backend = context.socket(ZMQ.DEALER);
    backend.bind("tcp://*:5560");

    //  Start the proxy
    ZMQ.proxy (frontend, backend, null);

    //  We never get here but clean up anyhow
    frontend.close();
    backend.close();
    context.term();
}
 
Example #11
Source File: Session.java    From jupyter-kernel-jsr223 with Apache License 2.0 5 votes vote down vote up
public static void runKernelDebug(Session session) throws FileNotFoundException,
        InvalidKeyException,
        UnsupportedEncodingException,
        IOException {
    Session._DEBUG_ = true;
    ZContext ctx = new ZContext();
    Socket channel = ctx.createSocket(ZMQ.REP);
    channel.bind("tcp://127.0.0.1:2222");
    byte[] msg = channel.recv();
    String sArgs = new String(msg, StandardCharsets.UTF_8);
    String[] newArgs = sArgs.split(" ");
    channel.send("ok");
    runKernel(session, newArgs);
}
 
Example #12
Source File: AsyncBankServiceImpl.java    From ignite-book-code-samples with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void execute(ServiceContext serviceContext) throws Exception {
    ObjectMapper objectMapper = new ObjectMapper();
    Context context = ZMQ.context(1);

    //  Socket to talk to server
    Socket responder = context.socket(ZMQ.REP);
    responder.connect(zeroMqBrokerAddress);
    ZMQ.PollItem items[] = {new ZMQ.PollItem(responder, ZMQ.Poller.POLLIN)};
    while (!Thread.currentThread().isInterrupted() && !serviceContext.isCancelled()) {
        //  Wait for next request from client
        int rc = ZMQ.poll(items, 1000);
        if (rc == -1) {
            continue;
        }

        if (items[0].isReadable()) {
            String reqStr = responder.recvStr(0);
            System.out.printf("Received request: [%s]\n", reqStr);

            ValidateRequest req = objectMapper.readValue(reqStr, ValidateRequest.class);

            ValidateResponse result = validateOperation(req.getAccount(), req.getSum());
            System.out.printf("send response request: [%s]\n", result);

            responder.send(objectMapper.writeValueAsString(result));
        }
    }
    System.out.println("Stop async read!");

    //  We never get here but clean up anyhow
    responder.close();
    context.term();

}
 
Example #13
Source File: WebMQSubscriber.java    From XRTB with Apache License 2.0 5 votes vote down vote up
public WebMQSubscriber(HttpServletResponse response, String port, String topics) {
	  // Prepare our context and subscriber
	
	
       Context context = ZMQ.context(1);
       Socket subscriber = context.socket(ZMQ.SUB);

       subscriber.connect("tcp://localhost:" + port);
       
       String [] parts = topics.split(",");
       for (String topic : parts) {
       	subscriber.subscribe(topic.getBytes());
       }

       while (!Thread.currentThread ().isInterrupted ()) {
           // Read envelope with address
           String address = subscriber.recvStr ();
           // Read message contents
           String contents = subscriber.recvStr ();
           Map m = new HashMap();
           m.put("topic", address);
           m.put("message", contents);
          
           try {
           	contents = mapper.writeValueAsString(m);
			response.getWriter().println(contents);
			response.flushBuffer();       	
		} catch (IOException e) {
			//e.printStackTrace();
			break;
		}               
       }
       subscriber.close ();
       context.term ();
}
 
Example #14
Source File: Proxy.java    From aion with MIT License 5 votes vote down vote up
private static boolean msgProcessRecv(Socket receiver, Socket sender, Socket hb) {
    byte[] msg = receiver.recv(0);
    if (msg == null) {
        return true;
    }

    byte[] msgMore = null;
    if (receiver.hasReceiveMore()) {
        msgMore = receiver.recv(0);

        if (msgMore == null) {
            return true;
        }
    }

    if (heartBeatMsg(msgMore)) {
        if (!hb.send(msg, ZMQ.SNDMORE)) {
            return true;
        }

        return !hb.send(msgMore, ZMQ.DONTWAIT);
    } else {
        if (!sender.send(msg, msgMore == null ? ZMQ.DONTWAIT : ZMQ.SNDMORE)) {
            return true;
        }

        if (msgMore != null) {
            return !sender.send(msgMore, ZMQ.DONTWAIT);
        }
    }

    return false;
}
 
Example #15
Source File: ZFrame.java    From aion with MIT License 5 votes vote down vote up
/**
 * Method to call org.zeromq.Socket send() method.
 * @param socket
 *            0MQ socket to send on
 * @param flags
 *            Valid send() method flags, defined in org.zeromq.ZMQ class
 * @return True if success, else False
 */
public boolean send(Socket socket, int flags)
{
    // Note the jzmq Socket.cpp JNI class does a memcpy of the byte data
    // before calling
    // the 0MQ send function, so don't have to clone the message data again
    // here.
    return socket.send(hasData() ? data : new byte[0], flags);
}
 
Example #16
Source File: ZMQQueue.java    From aion with MIT License 5 votes vote down vote up
/**
 * Class constructor.
 * 
 * @param context a 0MQ context previously created.
 * @param inSocket input socket
 * @param outSocket output socket
 */
public ZMQQueue(Context context, Socket inSocket, Socket outSocket) {
    this.inSocket = inSocket;
    this.outSocket = outSocket;

    this.poller = context.poller(2);
    this.poller.register(inSocket, ZMQ.Poller.POLLIN);
    this.poller.register(outSocket, ZMQ.Poller.POLLIN);
}
 
Example #17
Source File: ZContext.java    From aion with MIT License 5 votes vote down vote up
/**
 * 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) {
    if (context == null)
        context = ZMQ.context(ioThreads);

    // Create and register socket
    Socket socket = context.socket(type);
    sockets.add(socket);
    return socket;
}
 
Example #18
Source File: ZContext.java    From aion with MIT License 5 votes vote down vote up
/**
 * Class Constructor
 */
public ZContext() {
    context = null; // Don't create Context until create 1st 0MQ socket
    sockets = new CopyOnWriteArrayList<Socket>();
    ioThreads = 1;
    linger = 0;
    main = true;
}
 
Example #19
Source File: ZContext.java    From aion with MIT License 5 votes vote down vote up
/**
 * Destructor. Call this to gracefully terminate context and close any managed 0MQ sockets
 */
public void destroy() {
    ListIterator<Socket> itr = sockets.listIterator();
    while (itr.hasNext()) {
        destroySocket(itr.next());
    }
    sockets.clear();

    // Only terminate context if we are on the main thread
    if (isMain() && context != null)
        context.term();

}
 
Example #20
Source File: ZAuth.java    From aion with MIT License 5 votes vote down vote up
@Override
public void run(Object[] args, ZContext ctx, Socket pipe) {
    this.pipe = pipe;

    //create ZAP handler and get ready for requests
    handler = ctx.createSocket(ZMQ.REP);
    try {
        handler.bind("inproc://zeromq.zap.01");
    } catch (ZMQException e) {
        pipe.send("ERROR");
        return;
    }

    pipe.send("OK");

    PollItem[] pollItems = {new PollItem(pipe, Poller.POLLIN), new PollItem(handler, Poller.POLLIN)};
    while (!terminated && !Thread.currentThread().isInterrupted()) {
        int rc = ZMQ.poll(pollItems, -1);
        if (rc == -1) {
            break; //interrupt

        }

        if (pollItems[0].isReadable()) {
            if (!controlMessage()) {
                break;
            }
        }

        if (pollItems[1].isReadable()) {
            if (!authenticate()) {
                break;
            }
        }
    }
}
 
Example #21
Source File: ZFrame.java    From aion with MIT License 5 votes vote down vote up
/**
 * Receive a new frame off the socket, Returns newly-allocated frame, or
 * null if there was no input waiting, or if the read was interrupted.
 * @param socket
 *            Socket to read from
 * @param flags
 *            Pass flags to 0MQ socket.recv call
 * @return received frame, else null
 */
public static ZFrame recvFrame(Socket socket, int flags)
{
    ZFrame f = new ZFrame();
    byte[] data = f.recv(socket, flags);
    if (data == null) {
        f = null;
    }
    return f;
}
 
Example #22
Source File: ZAuth.java    From aion with MIT License 5 votes vote down vote up
static ZAPRequest recvRequest(Socket handler) {
    if (ZMQ.getMajorVersion() == 4) {
        ZMsg request = ZMsg.recvMsg(handler);
        ZAPRequest self = new ZAPRequest();

        //  Store handler socket so we can send a reply easily
        self.handler = handler;

        //  Get all standard frames off the handler socket
        self.version = request.popString();
        self.sequence = request.popString();
        self.domain = request.popString();
        self.address = request.popString();
        self.identity = request.popString();
        self.mechanism = request.popString();

        //  If the version is wrong, we're linked with a bogus libzmq, so die
        assert (self.version.equals("1.0"));

        // Get mechanism-specific frames
        if (self.mechanism.equals("PLAIN")) {
            self.username = request.popString();
            self.password = request.popString();
        } else if (self.mechanism.equals("CURVE")) {
        	ZFrame frame = request.pop();
        	byte[] clientPublicKey = frame.getData();
        	self.clientKey = ZMQ.Curve.z85Encode(clientPublicKey);
        } else if (self.mechanism.equals("GSSAPI")) {
            self.principal = request.popString();
        }

        request.destroy();
        return self;
    } else {
        return null;
    }
}
 
Example #23
Source File: ZThread.java    From aion with MIT License 5 votes vote down vote up
protected ShimThread(ZContext ctx, IAttachedRunnable runnable, Object[] args, Socket pipe) {
    assert (ctx != null);
    assert (pipe != null);
    assert (runnable != null);

    this.ctx = ctx;
    this.attachedRunnable = runnable;
    this.args = args;
    this.pipe = pipe;
}
 
Example #24
Source File: ZMQForwarder.java    From aion with MIT License 5 votes vote down vote up
/**
 * Class constructor.
 * 
 * @param context a 0MQ context previously created.
 * @param inSocket input socket
 * @param outSocket output socket
 */
public ZMQForwarder(Context context, Socket inSocket, Socket outSocket) {
    this.inSocket = inSocket;
    this.outSocket = outSocket;

    this.poller = context.poller(1);
    this.poller.register(inSocket, ZMQ.Poller.POLLIN);
}
 
Example #25
Source File: ZmqSendingMessageHandler.java    From spring-integration-zmq with Apache License 2.0 4 votes vote down vote up
public void run() {
	
	Socket socket = null;
	
	synchronized (startupMonitor) {
		try {
			socket = contextManager.context().createSocket(socketType);
			if (bind) {
				socket.bind(address);
			} else {
				socket.connect(address);
			}
		} finally {
			startupMonitor.notify();
		}
	}
	
	while (!Thread.currentThread().isInterrupted()) {
		try {
			Message<?> message = messageQueue.take();
			byte[] payload = converter.convert(message.getPayload());
			if (topicBytes == null) {
				socket.send(payload);
			} else {
				byte[] msgTopic = null;
				if (message.getHeaders().containsKey("zmq.topic")) {
					msgTopic = message.getHeaders().get("zmq.topic", String.class).getBytes(ZMQ.CHARSET);
				} else {
					msgTopic = topicBytes;
				}
				byte[] topicPayload = new byte[msgTopic.length + payload.length];
				System.arraycopy(msgTopic, 0, topicPayload, 0, msgTopic.length);
				System.arraycopy(payload, 0, topicPayload, msgTopic.length, payload.length);
				socket.send(topicPayload);
			}
		} catch (Throwable t) {
               if (!running) {
               	break;
               }
               logger.error("Exception in zmq sending message handler", t);
		}
	}
	
	socket.close();
}
 
Example #26
Source File: MessageObject.java    From jupyter-kernel-jsr223 with Apache License 2.0 4 votes vote down vote up
public MessageObject(ZMsg zmsg, Socket socket, byte[] key) {
    this.socket = socket;
    this.key = key;
    this.zmsg = zmsg;
    this.msg = new T_message();
}
 
Example #27
Source File: MsgExecutor.java    From aion_api with MIT License 4 votes vote down vote up
Socket getNbSocket() {
    return nbSocket;
}
 
Example #28
Source File: MsgExecutor.java    From aion_api with MIT License 4 votes vote down vote up
private boolean msgHandle(
        Socket receiver, Socket sender, Socket sender2, Socket sender3, Socket sender4) {

    byte[] msg = receiver.recv(ZMQ.PAIR);
    if (msg == null) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("[msgHandle] {}", ErrId.getErrString(-322L));
        }
        return false;
    }

    if (msg.length < ApiUtils.RSP_HEADER_NOHASH_LEN) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("[msgHandle] {}", ErrId.getErrString(-321L));
        }
        return false;
    }

    if (msg[1] > Message.Retcode.r_tx_Recved_VALUE) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("[msgHandle]" + " forward to txSender.");
        }

        if (!sender2.send(msg, ZMQ.PAIR)) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("[msgHandle] txSender{}", ErrId.getErrString(-323L));
            }
            return false;
        }

    } else if (msg[1] == Message.Retcode.r_heartbeatReturn_VALUE) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("[msgHandle] forward to hbDealer.");
        }
        if (!sender4.send(msg, ZMQ.PAIR)) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("[msgHandle] hbDealer{}", ErrId.getErrString(-323L));
            }
            return false;
        }
    } else {
        if (msg[2] == 0) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[msgHandle] forward to nonBlockSender.");
            }
            if (!sender3.send(msg, ZMQ.PAIR)) {
                if (LOGGER.isErrorEnabled()) {
                    LOGGER.error("[msgHandle] nonBlockSender{}", ErrId.getErrString(-323L));
                }
                return false;
            }
        } else {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("[msgHandle] forward to normalSender.");
            }
            if (!sender.send(msg, ZMQ.PAIR)) {
                if (LOGGER.isErrorEnabled()) {
                    LOGGER.error("[msgHandle] regularSender{}", ErrId.getErrString(-323L));
                }
                return false;
            }
        }
    }

    return true;
}
 
Example #29
Source File: MsgExecutor.java    From aion_api with MIT License 4 votes vote down vote up
private void proxy(
        Socket feSocket, Socket beSocket, Socket cbSocket, Socket nbDealer, Socket hbDealer) {
    PollItem[] items = new PollItem[4];
    items[0] = new PollItem(feSocket, ZMQ.Poller.POLLIN);
    items[1] = new PollItem(beSocket, ZMQ.Poller.POLLIN);
    items[2] = new PollItem(nbDealer, ZMQ.Poller.POLLIN);
    items[3] = new PollItem(hbDealer, ZMQ.Poller.POLLIN);

    try {
        this.isInitialized.set(true);

        while (this.running) {
            //  Wait while there are either requests or replies to process.
            int rc = ZMQ.poll(items, 3000);
            if (rc < 1) {
                if (this.running && LOGGER.isDebugEnabled()) {
                    LOGGER.debug("ZMQ.poll error rc:{}", rc);
                }
                continue;
            }

            //  Process a reply.
            if (items[0].isReadable()) {
                while (true) {
                    if (!msgHandle(feSocket, beSocket, cbSocket, nbDealer, hbDealer)) {
                        throw new Exception("ZMQ items[0] handle abnormal!");
                    }
                    break;
                }
            }
            //  Process a request.
            if (items[1].isReadable()) {
                while (true) {
                    if (invalidMsgHandle(beSocket, feSocket)) {
                        throw new Exception("ZMQ items[1] handle abnormal!");
                    }
                    break;
                }
            }

            //  Process a request.
            if (items[2].isReadable()) {
                while (true) {
                    if (invalidMsgHandle(nbDealer, feSocket)) {
                        throw new Exception("ZMQ items[2] handle abnormal!");
                    }
                    break;
                }
            }

            if (items[3].isReadable()) {
                while (true) {
                    if (invalidMsgHandle(hbDealer, feSocket)) {
                        throw new Exception("ZMQ items[3] handle abnormal!");
                    }
                    break;
                }
            }
        }
    } catch (Exception e) {
        if (LOGGER.isErrorEnabled()) {
            LOGGER.error("proxy exception: [{}]", e.getMessage());
        }
    }

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("socket proxy exit!");
    }
}
 
Example #30
Source File: MsgExecutor.java    From aion_api with MIT License 4 votes vote down vote up
private void workerRun(Context ctx) {
    Socket worker = ctx.socket(ZMQ.DEALER);
    worker.connect(WK_BIND_ADDR + addrBindNumber);
    worker.setReceiveTimeOut(RECVTIMEOUT);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("connected!");
    }

    while (true) {
        MsgReq msg = null;
        try {
            msg = queue.poll(RECVTIMEOUT, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (!this.running) {
            break;
        }

        if (msg != null && msg.req != null) {
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("poll q: [{}]", IUtils.bytes2Hex(msg.hash));
            }

            if (!worker.send(msg.req, ZMQ.PAIR)) {
                if (LOGGER.isErrorEnabled()) {
                    LOGGER.error("send msg failed. Msg: [{}]", IUtils.bytes2Hex(msg.req));
                }
                continue;
            }

            byte[] rsp = worker.recv(ZMQ.PAIR);
            if (this.running) {
                if (rsp == null) {
                    if (LOGGER.isErrorEnabled()) {
                        LOGGER.error("recv msg: [null]");
                    }
                    return;
                }

                if (LOGGER.isDebugEnabled()) {
                    LOGGER.debug("recv msg: [{}]", IUtils.bytes2Hex(rsp));
                }
                process(rsp);
            } else {
                break;
            }
        }
    }

    LOGGER.info("closing!");
    worker.close();
    LOGGER.info("closed!");
}