org.zeromq.ZMQ Java Examples

The following examples show how to use org.zeromq.ZMQ. 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: Pull.java    From XRTB with Apache License 2.0 8 votes vote down vote up
public Pull(HttpServletResponse response, String port, String timeout, String limit) throws Exception {
	int lim = 1;
	if (limit != null) {
		lim = Integer.parseInt(limit);
	}
	ZMQ.Context context = ZMQ.context(1);
	ZMQ.Socket rcv = context.socket(ZMQ.PULL);
	rcv.bind("tcp://*:" + port);
	if (timeout != null) {
		int t = Integer.parseInt(timeout);
		rcv.setReceiveTimeOut(t);
	}
	
	int k = 0;
	while(k < lim || lim == 0) {
		String str = rcv.recvStr();		
		response.getWriter().println(str);
		k++;
	}
	
	rcv.close();
	context.term();
}
 
Example #2
Source File: Pull.java    From bidder with Apache License 2.0 7 votes vote down vote up
public Pull(HttpServletResponse response, String port, String timeout, String limit) throws Exception {
	int lim = 1;
	if (limit != null) {
		lim = Integer.parseInt(limit);
	}
	ZMQ.Context context = ZMQ.context(1);
	ZMQ.Socket rcv = context.socket(ZMQ.PULL);
	rcv.bind("tcp://*:" + port);
	if (timeout != null) {
		int t = Integer.parseInt(timeout);
		rcv.setReceiveTimeOut(t);
	}
	
	int k = 0;
	while(k < lim || lim == 0) {
		String str = rcv.recvStr();		
		response.getWriter().println(str);
		k++;
	}
	
	rcv.close();
	context.term();
}
 
Example #3
Source File: ConnectionManager.java    From trex-stateless-gui with Apache License 2.0 6 votes vote down vote up
private boolean connectToZMQ() {
    connectionString = "tcp://" + ip + ":" + rpcPort;
    try {
        LogsController.getInstance().appendText(LogType.INFO, "Connecting to Trex server: " + connectionString);
        requester = buildRequester();
        requester.connect(connectionString);
        poller.register(requester, ZMQ.Poller.POLLIN);
        LogsController.getInstance().appendText(LogType.INFO, "Connected");
    } catch (Exception ex) {
        LOG.error("Invalid hostname", ex);
        return false;
    }

    // Just try to connect but don't account
    scapyServerClient.connect("tcp://" + ip + ":" + scapyPort, timeout);

    return true;
}
 
Example #4
Source File: XPublisher.java    From bidder with Apache License 2.0 6 votes vote down vote up
public XPublisher(String binding, String topicName) throws Exception {
    super();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    context = ZMQ.context(1);
    publisher = context.socket(ZMQ.XPUB);
    publisher.bind(binding);

    Thread.sleep(100);
    //System.out.println("Starting Publisher..");
    publisher.setIdentity("B".getBytes());
    publisher.setLinger(5000);
    publisher.setHWM(0);

    this.topicName = topicName;
}
 
Example #5
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 #6
Source File: WebMQPublisher.java    From bidder with Apache License 2.0 6 votes vote down vote up
public WebMQPublisher(String port, String topic, String message) throws Exception {

		String binding = "tcp://*:" + port;
		context = ZMQ.context(1);
		publisher = context.socket(ZMQ.PUB);
		publisher.bind(binding);
		Thread.sleep(1000);
		publisher.setIdentity("B".getBytes());
		publisher.setLinger(5000);
		publisher.setHWM(0);

		publisher.sendMore(topic);
		boolean isSent = publisher.send(message);
		publisher.close();
		context.term();
	}
 
Example #7
Source File: Publisher.java    From bidder with Apache License 2.0 6 votes vote down vote up
public Publisher(String binding, String topicName) throws Exception {

		mapper.setSerializationInclusion(Include.NON_NULL);
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		
		context = ZMQ.context(1);
		publisher = context.socket(ZMQ.PUB);

		if (binding.contains("*"))
			publisher.bind(binding);
		else
			publisher.connect(binding);

		Thread.sleep(100);
		//System.out.println("Starting Publisher..");
		publisher.setIdentity("B".getBytes());
		publisher.setLinger(5000);
		publisher.setHWM(100000);

		this.topicName = topicName;
	}
 
Example #8
Source File: WebMQPublisher.java    From XRTB with Apache License 2.0 6 votes vote down vote up
public WebMQPublisher(String port, String topic, String message) throws Exception {

		String binding = "tcp://*:" + port;
		context = ZMQ.context(1);
		publisher = context.socket(ZMQ.PUB);
		publisher.bind(binding);
		Thread.sleep(1000);
		publisher.setIdentity("B".getBytes());
		publisher.setLinger(5000);
		publisher.setHWM(0);

		publisher.sendMore(topic);
		boolean isSent = publisher.send(message);
		publisher.close();
		context.term();
	}
 
Example #9
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 #10
Source File: KernelSocketsZMQ.java    From beakerx with Apache License 2.0 6 votes vote down vote up
private synchronized void sendMsg(ZMQ.Socket socket, List<Message> messages) {
  if (!isShutdown()) {
    messages.forEach(message -> {
      String header = toJson(message.getHeader());
      String parent = toJson(message.getParentHeader());
      String meta = toJson(message.getMetadata());
      String content = toJson(message.getContent());
      String digest = hmac.sign(Arrays.asList(header, parent, meta, content));

      ZMsg newZmsg = new ZMsg();
      message.getIdentities().forEach(newZmsg::add);
      newZmsg.add(DELIM);
      newZmsg.add(digest.getBytes(StandardCharsets.UTF_8));
      newZmsg.add(header.getBytes(StandardCharsets.UTF_8));
      newZmsg.add(parent.getBytes(StandardCharsets.UTF_8));
      newZmsg.add(meta.getBytes(StandardCharsets.UTF_8));
      newZmsg.add(content.getBytes(StandardCharsets.UTF_8));
      message.getBuffers().forEach(x -> newZmsg.add(x));
      newZmsg.send(socket);
    });
  }
}
 
Example #11
Source File: Aion.java    From aion with MIT License 6 votes vote down vote up
private static void checkZmqKeyPair() throws IOException {
    File zmqkeyDir =
            new File(System.getProperty("user.dir") + File.separator + CfgApiZmq.ZMQ_KEY_DIR);

    if (!zmqkeyDir.isDirectory()) {
        if (!zmqkeyDir.mkdir()) {
            System.out.println(
                    "zmq keystore directory could not be created. "
                            + "Please check user permissions or create directory manually.");
            System.exit(SystemExitCodes.INITIALIZATION_ERROR);
        }
        System.out.println();
    }

    if (!existZmqSecKeyFile(zmqkeyDir.toPath())) {
        System.out.print("Can't find zmq key pair, generate new pair! \n");
        ZMQ.Curve.KeyPair kp = ZMQ.Curve.generateKeyPair();
        genKeyFile(zmqkeyDir.getPath(), kp.publicKey, kp.secretKey);
    } else {
        System.out.print("Find zmq key pair! \n");
    }
}
 
Example #12
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 #13
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 #14
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 #15
Source File: ZeroMQMessageReceiver.java    From attic-apex-malhar with Apache License 2.0 6 votes vote down vote up
@Override
public void run()
{
  logger.debug("receiver running");
  while (!Thread.currentThread().isInterrupted() && !shutDown) {
    byte[] msg = subscriber.recv(ZMQ.NOBLOCK);
    // convert to HashMap and save the values for each key
    // then expect c to be 1000, b=20, a=2
    // and do count++ (where count now would be 30)
    if (msg == null || msg.length == 0) {
      continue;
    }
    String str = new String(msg);

    if (str.indexOf("{") == -1) {
      continue;
    }
    int eq = str.indexOf('=');
    String key = str.substring(1, eq);
    int value = Integer.parseInt(str.substring(eq + 1, str.length() - 1));
    logger.debug("\nsubscriber recv: {}", str);
    dataMap.put(key, value);
    count++;
    logger.debug("out of loop.. ");
  }
}
 
Example #16
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 #17
Source File: ZMQIntegrationTest.java    From netty-zmtp with Apache License 2.0 5 votes vote down vote up
@Theory
public void test_NettyBindRouter_ZmqConnectDealer(
    @FromDataPoints("identities") final String zmqIdentity,
    @FromDataPoints("identities") final String nettyIdentity,
    @FromDataPoints("versions") final ZMTPProtocol nettyProtocol
)
    throws TimeoutException, InterruptedException, ExecutionException {
  // XXX (dano): jeromq fails on identities longer than 127 bytes due to a signedness issue
  assumeFalse(MAX_IDENTITY.equals(zmqIdentity));

  final ZMTPSocket router = nettyBind(ROUTER, nettyIdentity, nettyProtocol);
  final ZMQ.Socket dealer = zmqConnect(ZMQ.DEALER, zmqIdentity);

  testReqRep(dealer, router, zmqIdentity);
}
 
Example #18
Source File: RTopic.java    From XRTB with Apache License 2.0 5 votes vote down vote up
public RTopic(String address) throws Exception {
	context = ZMQ.context(1);
	
	mapper.setSerializationInclusion(Include.NON_NULL);
	mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	
	if (address.contains("&")) {
		String [] parts = address.split("&");
		subscriber = new Subscriber(this,parts[0]);
		subscriber.subscribe(parts[1]);
	} else
		subscriber = new Subscriber(this,address);
}
 
Example #19
Source File: PushPull.java    From XRTB with Apache License 2.0 5 votes vote down vote up
public void push() {
	ZMQ.Context context = ZMQ.context(1);
	ZMQ.Socket sender = context.socket(ZMQ.PUSH);
	sender.connect("tcp://localhost:8086");
	sender.send("MESSAGE");
	sender.close();
	context.term();
}
 
Example #20
Source File: Push.java    From XRTB with Apache License 2.0 5 votes vote down vote up
public Push(String port, String message)  {
	ZMQ.Context context = ZMQ.context(1);
	ZMQ.Socket sender = context.socket(ZMQ.PUSH);
	sender.connect("tcp://localhost:" + port);
	sender.send(message);
	sender.close();
	context.term();
}
 
Example #21
Source File: ZMQIntegrationTest.java    From netty-zmtp with Apache License 2.0 5 votes vote down vote up
@Theory
public void test_ZmqBindDealer_NettyConnectRouter(
    @FromDataPoints("identities") final String zmqIdentity,
    @FromDataPoints("identities") final String nettyIdentity,
    @FromDataPoints("versions") final ZMTPProtocol nettyProtocol
)
    throws TimeoutException, InterruptedException, ExecutionException {
  // XXX (dano): jeromq fails on identities longer than 127 bytes due to a signedness issue
  assumeFalse(MAX_IDENTITY.equals(zmqIdentity));

  final ZMQ.Socket dealer = zmqBind(ZMQ.DEALER, zmqIdentity);
  final ZMTPSocket router = nettyConnect(ROUTER, nettyIdentity, nettyProtocol);
  testReqRep(dealer, router, zmqIdentity);
}
 
Example #22
Source File: SimpleSinglePortZeroMQPullInputOperator.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
@Override
public void setup(Context.OperatorContext ctx)
{
  context = ZMQ.context(1);
  sock = context.socket(ZMQ.PULL);
  sock.connect(zmqAddress);
}
 
Example #23
Source File: AbstractBaseZeroMQOutputOperator.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
@Override
public void setup(OperatorContext ctx)
{
  logger.debug("O/P setup");
  context = ZMQ.context(1);
  publisher = context.socket(ZMQ.PUB);
  publisher.bind(url);
  syncservice = context.socket(ZMQ.REP);
  syncservice.bind(syncUrl);
}
 
Example #24
Source File: RTopic.java    From XRTB with Apache License 2.0 5 votes vote down vote up
/**
 * A Topic handler that subscribes but has a publisher too.
 * @param paddress String. My TCP address for publishing.
 * @param addresses List. My TCP address and topics for listening.
 * @throws Exception
 */
public RTopic(String phandler, List<String> addresses) throws Exception {
	this(addresses);
	
	publisher = context.socket(ZMQ.PUB);
	publisher.bind(phandler);

	publisher.setIdentity("B".getBytes());
	publisher.setLinger(5000);
	publisher.setHWM(0);
}
 
Example #25
Source File: Subscriber.java    From XRTB with Apache License 2.0 5 votes vote down vote up
public Subscriber(EventIF handler, String address) throws Exception {
	this.handler = handler;
	subscriber = context.socket(ZMQ.SUB);

	subscriber.connect(address);
	me = new Thread(this);
	me.start();
}
 
Example #26
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 #27
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 #28
Source File: ZeroMQWrapperPush.java    From gsn with GNU General Public License v3.0 5 votes vote down vote up
@Override
public boolean initialize() {
	
	kryo.register(StreamElement4Rest.class);
	kryo.register(DataField[].class);

	AddressBean addressBean = getActiveAddressBean();
	
	structure = getActiveAddressBean().getOutputStructure();

	String _lport = addressBean.getPredicateValue("local_port");
	laddress = addressBean.getPredicateValue("local_address");

	if ( laddress == null || laddress.trim().length() == 0 ) 
		throw new RuntimeException( "The >local_address< parameter is missing from the ZeroMQ wrapper." );
	if (_lport != null){
		lport = Integer.parseInt(_lport); 
		if ( lport <= 0 || lport > 65535 ) 
			throw new RuntimeException( "The >local_port< parameter must be a valid port number." );
	} else {
		throw new RuntimeException( "The >local_port< parameter is missing from the ZeroMQ wrapper." );
	}
	
	ZContext ctx = Main.getZmqContext();
	receiver = ctx.createSocket(ZMQ.REP);
	receiver.bind("tcp://*:"+lport);
	receiver.setReceiveTimeOut(10000);

       return true;
}
 
Example #29
Source File: JeroMqTestClient.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public List<String> call() throws Exception {
    try (ZMQ.Socket subscriber = context.socket(ZMQ.SUB)) {
        subscriber.connect(endpoint);
        subscriber.subscribe(new byte[0]);
        for (int messageNum = 0; messageNum < receiveCount
                && !Thread.currentThread().isInterrupted(); messageNum++) {
            // Use trim to remove the tailing '0' character
            messages.add(subscriber.recvStr(0).trim());
        }
    }
    return messages;
}
 
Example #30
Source File: ZeroMQDeliveryAsync.java    From gsn with GNU General Public License v3.0 5 votes vote down vote up
public ZeroMQDeliveryAsync(String name){
	if (name.endsWith(":")){
		name = name.substring(0, name.length()-1);
	}
       this.name = name;
	context = Main.getZmqContext();
	// Socket to talk to clients
	publisher = context.createSocket(ZMQ.PUB);
	publisher.setLinger(5000);
	publisher.setSndHWM(0); // no limit
	publisher.bind("inproc://stream/"+name);
	Main.getZmqProxy().connectTo(name);
	closed = false;

}