Java Code Examples for org.zeromq.ZMQ.Socket#close()

The following examples show how to use org.zeromq.ZMQ.Socket#close() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
Source File: ProtocolProcessor.java    From aion with MIT License 4 votes vote down vote up
@Override
public void run() {
    LOG.info("Starting Aion Api Server <port={}>", cfgApi.getPort());
    String bindAddr = "tcp://" + cfgApi.getIp() + ":" + cfgApi.getPort();
    int msgTh = 5;

    try {
        // create context.
        Context ctx = ZMQ.context(1);

        // create router sock.
        Socket feSock = ctx.socket(ROUTER);
        if (cfgApi.isSecureConnectEnabledEnabled()) {
            // Currently the system will only load the first pair of the key files.
            loadCurveKeyPair();

            if (curveSecKey != null && curvePubKey != null) {
                feSock.setZAPDomain("global".getBytes());
                feSock.setCurveServer(true);
                feSock.setCurvePublicKey(curvePubKey);
                feSock.setCurveSecretKey(curveSecKey);
                LOG.info("Secure connection enabled!");
            } else {
                LOG.info(
                        "Can't find the keyfile for setup the connection. Secure connection disabled!");
            }
        } else {
            LOG.info("Secure connection disabled!");
        }

        feSock.setSndHWM(zmqHWM);
        feSock.bind(bindAddr);

        Socket wkSocks = ctx.socket(DEALER);
        wkSocks.bind(AION_ZMQ_WK_TH);

        Socket cbSock = ctx.socket(DEALER);
        cbSock.bind(AION_ZMQ_CB_TH);

        Socket evSock = ctx.socket(DEALER);
        evSock.bind(AION_ZMQ_EV_TH);

        Socket hbSock = ctx.socket(DEALER);
        hbSock.bind(AION_ZMQ_HB_TH);

        ExecutorService es = Executors.newFixedThreadPool(msgTh);
        es.execute(() -> callbackRun(ctx));
        es.execute(this::txWaitRun);
        es.execute(() -> eventRun(ctx));
        es.execute(() -> workerRun(ctx));
        es.execute(() -> hbRun(ctx));

        Proxy.proxy(feSock, wkSocks, cbSock, evSock, hbSock);

        if (LOG.isInfoEnabled()) {
            LOG.info("ProtocolProcessor.run thread finish.");
        }

        if (LOG.isInfoEnabled()) {
            LOG.info("Shutting down Zmq sockets...");
        }
        // Shutdown HdlrZmq
        ((HdlrZmq) handler).shutdown();
        // Shutdown ZmqSocket
        feSock.close();
        wkSocks.close();
        cbSock.close();
        evSock.close();
        hbSock.close();
        // Shutdown ExecutorService
        es.shutdown();

        ctx.close();
        if (LOG.isInfoEnabled()) {
            LOG.info("Shutdown Zmq sockets... Done!");
        }

    } catch (Exception e) {
        if (LOG.isErrorEnabled()) {
            LOG.error("ProtocolProcessor.run exception: " + e.getMessage());
        }
    }
}
 
Example 8
Source File: ProtocolProcessor.java    From aion with MIT License 4 votes vote down vote up
private void callbackRun(Context ctx) {
    Socket sock = ctx.socket(ZMQ.DEALER);
    sock.connect(AION_ZMQ_CB_TH);

    while (!shutDown.get()) {
        TxPendingStatus tps;
        try {
            tps = ((HdlrZmq) this.handler).getTxStatusQueue().take();
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            if (LOG.isErrorEnabled()) {
                LOG.error("queue take exception - [{}]", e1.getMessage());
            }
            continue;
        }

        if (tps.isEmpty()) {
            continue;
        }

        byte[] rsp =
                tps.toTxReturnCode() != 105
                        ? ((HdlrZmq) this.handler)
                                .toRspMsg(
                                        tps.getMsgHash(), tps.toTxReturnCode(), tps.getError())
                        : ((HdlrZmq) this.handler)
                                .toRspMsg(
                                        tps.getMsgHash(),
                                        tps.toTxReturnCode(),
                                        tps.getError(),
                                        tps.getTxResult());
        if (LOG.isTraceEnabled()) {
            LOG.trace(
                    "callbackRun send. socketID: [{}], msgHash: [{}], txReturnCode: [{}]/n rspMsg: [{}]",
                    Hex.toHexString(tps.getSocketId()),
                    Hex.toHexString(tps.getMsgHash()),
                    tps.toTxReturnCode(),
                    Hex.toHexString(rsp));
        }
        try {
            sock.send(tps.getSocketId(), ZMQ.SNDMORE);
            sock.send(rsp, ZMQ.DONTWAIT);
        } catch (Exception e) {
            if (LOG.isErrorEnabled()) {
                LOG.error(
                        "ProtocolProcessor.callbackRun sock.send exception: " + e.getMessage());
            }
        }
    }
    sock.close();
    if (LOG.isDebugEnabled()) {
        LOG.debug("close callbackRun sockets...");
    }
}
 
Example 9
Source File: MsgExecutor.java    From aion_api with MIT License 4 votes vote down vote up
private void heartBeatRun(Context ctx) {
    Socket hbWorker = ctx.socket(ZMQ.DEALER);
    hbWorker.connect(HB_BIND_ADDR + addrBindNumber);
    hbWorker.setReceiveTimeOut(1000);
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("hbWorker connected!");
    }

    int hbTolerance = HB_TOLERANCE;
    byte[] hbMsg = ApiUtils.toReqHeader(this.ver, Message.Servs.s_hb, Message.Funcs.f_NA);

    while (this.running && hbTolerance > 0) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("send hb!");
        }
        if (!hbWorker.send(hbMsg, ZMQ.DONTWAIT)) {
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("send heartbeat msg failed.");
            }
            continue;
        }

        byte[] rsp = hbWorker.recv(ZMQ.PAIR);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("recv msg: [{}]", (rsp != null ? IUtils.bytes2Hex(rsp) : "null"));
        }

        if (checkNotHbRspMsg(rsp)) {
            hbTolerance--;
        } else {
            hbTolerance = HB_TOLERANCE;
        }

        try {
            Thread.sleep(HB_POLL_MS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    if (this.running) {
        this.running = false;
        LOGGER.warn("timeout, disconnect the connection!");
        hbWorker.close();
        terminate();
        LOGGER.info("closed!");
    }
}
 
Example 10
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!");
}
 
Example 11
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();
}