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

The following examples show how to use org.zeromq.ZMQ.Socket#send() . 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: 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 2
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 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: 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 5
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 6
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 7
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 8
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 9
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 10
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 11
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 12
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 13
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();
}