当前位置: 首页>>代码示例>>Java>>正文


Java Poller.poll方法代码示例

本文整理汇总了Java中org.zeromq.ZMQ.Poller.poll方法的典型用法代码示例。如果您正苦于以下问题:Java Poller.poll方法的具体用法?Java Poller.poll怎么用?Java Poller.poll使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在org.zeromq.ZMQ.Poller的用法示例。


在下文中一共展示了Poller.poll方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: main

import org.zeromq.ZMQ.Poller; //导入方法依赖的package包/类
public static void main (String[] args)
{
    ZContext ctx = new ZContext ();

    //  Use the Zyre UDP class to make sure we listen on the same
    //  network interface as our peers
    ZreUdp udp = new ZreUdp (ZreInterface.PING_PORT_NUMBER);
    String host = udp.host ();
    Socket collector = ctx.createSocket (ZMQ.SUB);

    //  Bind to an ephemeral port
    int port = collector.bindToRandomPort (String.format ("tcp://%s", host));

    //  Announce this to all peers we connect to
    ZreInterface inf = new ZreInterface ();
    inf.setHeader ("X-ZRELOG", "tcp://%s:%d", host, port);

    //  Get all log messages (don't filter)
    collector.subscribe ("".getBytes ());

    Poller items = ctx.getContext ().poller ();
    
    items.register (collector, Poller.POLLIN);
    items.register (inf.handle (), Poller.POLLIN);
    
    while (!Thread.currentThread ().isInterrupted ()) {
        if (items.poll (1000) == -1)
            break;              //  Interrupted
        //  Handle input on collector
        if (items.pollin (0))
            printLogMsg (collector);

        //  Handle event from interface (ignore it)
        if (items.pollin (1)) {
            ZMsg msg = inf.recv ();
            if (msg == null)
                break;              //  Interrupted
            msg.destroy ();
        }
    }
    inf.destroy ();
    udp.destroy ();
    ctx.destroy ();

}
 
开发者ID:zeromq,项目名称:jyre,代码行数:46,代码来源:ZreLogger.java

示例2: sendRequest

import org.zeromq.ZMQ.Poller; //导入方法依赖的package包/类
private AldaResponse sendRequest(ZMsg request, int timeout, int retries)
  throws NoResponseException {
  // When non-null, used to help ensure that we don't use a response from the
  // server that was for a different request.
  String jobId = options == null ? null : options.jobId;

  while (retries >= 0 && !Thread.currentThread().isInterrupted()) {
    Poller poller = getPoller();
    Socket client = rebuildSocket();

    // false means don't destroy the message after sending
    request.send(client, false);

    int rc = poller.poll(timeout);
    if (rc == -1) {
      request.destroy();
      throw new NoResponseException("Connection interrupted.");
    }

    if (poller.pollin(0)) {
      ZMsg zmsg = ZMsg.recvMsg(client);
      if (debug) zmsg.dump();

      byte[] address = zmsg.unwrap().getData(); // discard envelope
      String responseJson = zmsg.popString();

      AldaResponse response = AldaResponse.fromJson(responseJson);

      // If there is a jobId option, we will ignore any response from the
      // server that doesn't have the same jobId, and try again. This will not
      // count against our remaining retries, as the server did respond.
      if (jobId != null &&
          response.jobId != null &&
          !jobId.equals(response.jobId))
        continue;

      if (!response.noWorker)
        response.workerAddress = zmsg.pop().getData();

      request.destroy();
      return response;
    }

    // Didn't get a response within the allowed timeout. Try again, unless
    // we're out of retries.
    retries--;
  }

  request.destroy();
  String errorMsg = "Alda server is down. To start the server, run `alda up`.";
  throw new NoResponseException(errorMsg);
}
 
开发者ID:alda-lang,项目名称:alda-client-java,代码行数:53,代码来源:AldaRequest.java

示例3: broadcastCommand

import org.zeromq.ZMQ.Poller; //导入方法依赖的package包/类
/**
 * Broadcast a command to a remote server.
 *
 * <p>Example: Send a signature command to the alternate cosigner server. It will respond with
 * signed data.
 *
 * @param command Command to broadcast.
 * @param server  Server to attempt to send the command to.
 * @return Reply from the server.
 */
public static String broadcastCommand(BaseCommand command, Server server) {
  // Update the comm time if we've actually been talking to this server.
  if (ClusterInfo.getInstance().getServers().contains(server)) {
    ClusterInfo.getInstance().getServers().forEach(trackedServer -> {
      if (trackedServer.equals(server)) {
        server.setLastCommunication(trackedServer.getLastCommunication());
      }
    });
  }

  // If we haven't heard from the server in more then 2 minutes, consider it offline.
  if ((System.currentTimeMillis() - server.getLastCommunication()) > 2 * 60 * 1000) {
    if (command.getClass() == ClusterCommand.class
        && ((ClusterCommand) command).getCommandType() == ClusterCommandType.HEARTBEAT) {
      LOGGER.debug("Server is too old, sending heartbeat");
    } else {
      LOGGER.debug("Server is too old, removing server");
      ClusterInfo.getInstance().getServers().remove(server);
      return "";
    }
  }

  // If it's not a ClusterCommand, encrypt it. ClusterCommands only identify servers, and
  // they're checked for signatures.
  if (command.getClass() != ClusterCommand.class) {
    command =
        new EncryptedCommand(ClusterInfo.getInstance().getThisServer(), ServerKey.getMykey(),
            server, command.toJson());
  }

  String commandString = command.toJson();

  Context context = ZMQ.context(1);
  Socket requester = context.socket(ZMQ.REQ);
  requester.connect("tcp://" + server.getServerLocation() + ":" + server.getServerRpcPort());

  requester.send(commandString);
  LOGGER.debug("Command is in flight");

  String reply = command.toJson();
  Poller poller = new Poller(1);
  poller.register(requester, Poller.POLLIN);

  poller.poll(REQUEST_TIMEOUT);

  if (poller.pollin(0)) {
    reply = requester.recvStr();
    LOGGER.debug("Got response");
  }

  requester.close();

  return reply;
}
 
开发者ID:Braveno,项目名称:cosigner,代码行数:65,代码来源:Coordinator.java

示例4: run

import org.zeromq.ZMQ.Poller; //导入方法依赖的package包/类
@Override
public void run (Object[] args, ZContext ctx, Socket pipe)
{
    Agent agent = Agent.newAgent (ctx, pipe);
    if (agent == null)   //  Interrupted
        return;
    
    long pingAt = System.currentTimeMillis ();
    Poller items = ctx.getContext ().poller ();
    
    items.register (agent.pipe, Poller.POLLIN);
    items.register (agent.inbox, Poller.POLLIN);
    items.register (agent.udp.handle (), Poller.POLLIN);
    
    while (!Thread.currentThread ().isInterrupted ()) {
        long timeout = pingAt - System.currentTimeMillis ();
        assert (timeout <= PING_INTERVAL);
        
        if (timeout < 0)
            timeout = 0;
        
        if (items.poll (timeout) < 0)
            break;      // Interrupted
        
        if (items.pollin (0))
            agent.recvFromApi ();
        
        if (items.pollin (1))
            agent.recvFromPeer ();
        
        if (items.pollin (2))
            agent.recvUdpBeacon ();
        
        if (System.currentTimeMillis () >= pingAt) {
            agent.sendBeacon ();
            pingAt = System.currentTimeMillis () + PING_INTERVAL;
            //  Ping all peers and reap any expired ones
            agent.pingAllPeers ();
        }
    }
    agent.destroy ();
}
 
开发者ID:zeromq,项目名称:jyre,代码行数:43,代码来源:ZreInterface.java

示例5: run

import org.zeromq.ZMQ.Poller; //导入方法依赖的package包/类
public void run() {

        ZContext ctx = new ZContext();

        Socket snapshot = ctx.createSocket(ZMQ.ROUTER);
        snapshot.bind("tcp://*:5556");

        Socket publisher = ctx.createSocket(ZMQ.PUB);
        publisher.bind("tcp://*:5557");

        Socket collector = ctx.createSocket(ZMQ.PULL);
        collector.bind("tcp://*:5558");

        Poller poller = new Poller(2);
        poller.register(collector, Poller.POLLIN);
        poller.register(snapshot, Poller.POLLIN);

        long sequence = 0;
        while (!Thread.currentThread().isInterrupted()) {
            if (poller.poll(1000) < 0)
                break;              //  Context has been shut down

            // apply state updates from main thread
            if (poller.pollin(0)) {
                kvsimple kvMsg = kvsimple.recv(collector);
                if (kvMsg == null)  //  Interrupted
                    break;
                kvMsg.setSequence(++sequence);
                kvMsg.send(publisher);
                clonesrv3.kvMap.put(kvMsg.getKey(), kvMsg);
                System.out.printf("I: publishing update %5d\n", sequence);
            }

            // execute state snapshot request
            if (poller.pollin(1)) {
                byte[] identity = snapshot.recv(0);
                if (identity == null)
                    break;      //  Interrupted
                String request = snapshot.recvStr();

                if (!request.equals("ICANHAZ?")) {
                    System.out.println("E: bad request, aborting");
                    break;
                }

                Iterator<Entry<String, kvsimple>> iter = kvMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Entry<String, kvsimple> entry = iter.next();
                    kvsimple msg = entry.getValue();
                    System.out.println("Sending message " + entry.getValue().getSequence());
                    this.sendMessage(msg, identity, snapshot);
                }

                // now send end message with getSequence number
                System.out.println("Sending state snapshot = " + sequence);
                snapshot.send(identity, ZMQ.SNDMORE);
                kvsimple message = new kvsimple("KTHXBAI", sequence, ZMQ.SUBSCRIPTION_ALL);
                message.send(snapshot);
            }
        }
        System.out.printf (" Interrupted\n%d messages handled\n", sequence);
        ctx.destroy();
    }
 
开发者ID:zeromq,项目名称:jeromq3-x,代码行数:64,代码来源:clonesrv3.java

示例6: main

import org.zeromq.ZMQ.Poller; //导入方法依赖的package包/类
public static void main (String[] args) {
    //  Prepare our context and sockets
    Context context = ZMQ.context(1);

    Socket frontend = context.socket(ZMQ.ROUTER);
    Socket backend  = context.socket(ZMQ.DEALER);
    frontend.bind("tcp://*:5559");
    backend.bind("tcp://*:5560");

    System.out.println("launch and connect broker.");

    //  Initialize poll set
    Poller items = new Poller (2);
    items.register(frontend, Poller.POLLIN);
    items.register(backend, Poller.POLLIN);

    boolean more = false;
    byte[] message;

    //  Switch messages between sockets
    while (!Thread.currentThread().isInterrupted()) {            
        //  poll and memorize multipart detection
        items.poll();

        if (items.pollin(0)) {
            while (true) {
                // receive message
                message = frontend.recv(0);
                more = frontend.hasReceiveMore();

                // Broker it
                backend.send(message, more ? ZMQ.SNDMORE : 0);
                if(!more){
                    break;
                }
            }
        }
        if (items.pollin(1)) {
            while (true) {
                // receive message
                message = backend.recv(0);
                more = backend.hasReceiveMore();
                // Broker it
                frontend.send(message,  more ? ZMQ.SNDMORE : 0);
                if(!more){
                    break;
                }
            }
        }
    }
    //  We never get here but clean up anyhow
    frontend.close();
    backend.close();
    context.term();
}
 
开发者ID:zeromq,项目名称:jeromq3-x,代码行数:56,代码来源:rrbroker.java

示例7: run

import org.zeromq.ZMQ.Poller; //导入方法依赖的package包/类
public void run() {

        ZContext ctx = new ZContext();

        Socket snapshot = ctx.createSocket(ZMQ.ROUTER);
        snapshot.bind("tcp://*:5556");

        Socket publisher = ctx.createSocket(ZMQ.PUB);
        publisher.bind("tcp://*:5557");

        Socket collector = ctx.createSocket(ZMQ.PULL);
        collector.bind("tcp://*:5558");

        Poller poller = new Poller(2);
        poller.register(collector, Poller.POLLIN);
        poller.register(snapshot, Poller.POLLIN);

        long sequence = 0;
        while (!Thread.currentThread().isInterrupted()) {
            if (poller.poll(1000) < 0)
                break;              //  Context has been shut down

            // apply state updates from main thread
            if (poller.pollin(0)) {
                kvsimple kvMsg = kvsimple.recv(collector);
                if (kvMsg == null)  //  Interrupted
                    break;
                kvMsg.setSequence(++sequence);
                kvMsg.send(publisher);
                clonesrv4.kvMap.put(kvMsg.getKey(), kvMsg);
                System.out.printf("I: publishing update %5d\n", sequence);
            }

            // execute state snapshot request
            if (poller.pollin(1)) {
                byte[] identity = snapshot.recv(0);
                if (identity == null)
                    break;      //  Interrupted

                //  .until
                //  Request is in second frame of message
                String request = snapshot.recvStr();

                if (!request.equals("ICANHAZ?")) {
                    System.out.println("E: bad request, aborting");
                    break;
                }

                String subtree = snapshot.recvStr();


                Iterator<Entry<String, kvsimple>> iter = kvMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Entry<String, kvsimple> entry = iter.next();
                    kvsimple msg = entry.getValue();
                    System.out.println("Sending message " + entry.getValue().getSequence());
                    this.sendMessage(msg, identity, subtree, snapshot);
                }

                // now send end message with getSequence number
                System.out.println("Sending state snapshot = " + sequence);
                snapshot.send(identity, ZMQ.SNDMORE);
                kvsimple message = new kvsimple("KTHXBAI", sequence, ZMQ.SUBSCRIPTION_ALL);
                message.send(snapshot);
            }
        }
        System.out.printf (" Interrupted\n%d messages handled\n", sequence);
        ctx.destroy();
    }
 
开发者ID:zeromq,项目名称:jeromq3-x,代码行数:70,代码来源:clonesrv4.java

示例8: run

import org.zeromq.ZMQ.Poller; //导入方法依赖的package包/类
@Override
public void run(Object[] args, ZContext ctx, Socket pipe) {
	pipe.send("READY"); // optional

	Socket snapshot = ctx.createSocket(ZMQ.ROUTER);
	snapshot.bind("tcp://*:5556");

	Poller poller = new ZMQ.Poller(2);
	poller.register(pipe, ZMQ.Poller.POLLIN);
	poller.register(snapshot, ZMQ.Poller.POLLIN);

	long stateSequence = 0;
	while (!Thread.currentThread().isInterrupted()) {
		if (poller.poll() < 0)
                  break;              //  Context has been shut down

		// apply state updates from main thread
		if (poller.pollin(0)) {
			kvsimple kvMsg = kvsimple.recv(pipe);
                  if (kvMsg == null)
                      break;
			StateManager.kvMap.put(kvMsg.getKey(), kvMsg);
			stateSequence = kvMsg.getSequence();
		}

		// execute state snapshot request
		if (poller.pollin(1)) {
			byte[] identity = snapshot.recv(0);
                  if (identity == null)
                      break;
			String request = new String(snapshot.recv(0), ZMQ.CHARSET);

                  if (!request.equals("ICANHAZ?")) {
                      System.out.println("E: bad request, aborting");
                      break;
                  }

                  Iterator<Entry<String, kvsimple>> iter = kvMap.entrySet().iterator();
                  while (iter.hasNext()) {
                      Entry<String, kvsimple> entry = iter.next();
                      kvsimple msg = entry.getValue();
                      System.out.println("Sending message " + entry.getValue().getSequence());
                      this.sendMessage(msg, identity, snapshot);
                  }

                  // now send end message with getSequence number
                  System.out.println("Sending state snapshot = " + stateSequence);
                  snapshot.send(identity, ZMQ.SNDMORE);
                  kvsimple message = new kvsimple("KTHXBAI", stateSequence, ZMQ.MESSAGE_SEPARATOR);
                  message.send(snapshot);
		}
	}
}
 
开发者ID:zeromq,项目名称:jeromq3-x,代码行数:54,代码来源:clonesrv2.java


注:本文中的org.zeromq.ZMQ.Poller.poll方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。