Java Code Examples for org.zeromq.ZMQ.Socket#connect()
The following examples show how to use
org.zeromq.ZMQ.Socket#connect() .
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: ZThread.java From aion with MIT License | 6 votes |
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 2
Source File: MsgExecutor.java From aion_api with MIT License | 6 votes |
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 |
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: AsyncBankServiceImpl.java From ignite-book-code-samples with GNU General Public License v3.0 | 5 votes |
@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 5
Source File: WebMQSubscriber.java From XRTB with Apache License 2.0 | 5 votes |
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 6
Source File: ProtocolProcessor.java From aion with MIT License | 4 votes |
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 7
Source File: MsgExecutor.java From aion_api with MIT License | 4 votes |
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 8
Source File: MsgExecutor.java From aion_api with MIT License | 4 votes |
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 9
Source File: ZmqSendingMessageHandler.java From spring-integration-zmq with Apache License 2.0 | 4 votes |
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(); }