使用javajeromq的异步客户机/服务器

使用javajeromq的异步客户机/服务器,java,zeromq,jeromq,Java,Zeromq,Jeromq,我使用的是0.4.0版本的jeromq,我试图使用下面的例子,但这行ZMQ.poll(项目10)给出了编译错误。在最新版本的jeromq中,似乎发生了一些变化,但文档和代码尚未更新。有谁能帮助我了解如何调整我下面的代码以与最新版本的jeromq配合使用 <dependency> <groupId>org.zeromq</groupId> <artifactId>jeromq</artifactId>

我使用的是
0.4.0
版本的
jeromq
,我试图使用下面的例子,但这行
ZMQ.poll(项目10)给出了编译错误。在最新版本的
jeromq
中,似乎发生了一些变化,但文档和代码尚未更新。有谁能帮助我了解如何调整我下面的代码以与最新版本的
jeromq
配合使用

    <dependency>
        <groupId>org.zeromq</groupId>
        <artifactId>jeromq</artifactId>
        <version>0.4.0</version>
    </dependency>

org.zeromq
杰罗姆
0.4.0
代码如下:

public class asyncsrv {
  // ---------------------------------------------------------------------
  // This is our client task
  // It connects to the server, and then sends a request once per second
  // It collects responses as they arrive, and it prints them out. We will
  // run several client tasks in parallel, each with a different random ID.
  private static Random rand = new Random(System.nanoTime());

  private static class client_task implements Runnable {

    public void run() {
      ZContext ctx = new ZContext();
      Socket client = ctx.createSocket(ZMQ.DEALER);

      // Set random identity to make tracing easier
      String identity = String.format("%04X-%04X", rand.nextInt(), rand.nextInt());
      client.setIdentity(identity.getBytes());
      client.connect("tcp://localhost:5570");

      PollItem[] items = new PollItem[] {new PollItem(client, Poller.POLLIN)};

      int requestNbr = 0;
      while (!Thread.currentThread().isInterrupted()) {
        // Tick once per second, pulling in arriving messages
        for (int centitick = 0; centitick < 100; centitick++) {
          // this line is giving compilation error as it says undefined
          ZMQ.poll(items, 10);
          if (items[0].isReadable()) {
            ZMsg msg = ZMsg.recvMsg(client);
            msg.getLast().print(identity);
            msg.destroy();
          }
        }
        client.send(String.format("request #%d", ++requestNbr), 0);
      }
      ctx.destroy();
    }
  }

  // This is our server task.
  // It uses the multithreaded server model to deal requests out to a pool
  // of workers and route replies back to clients. One worker can handle
  // one request at a time but one client can talk to multiple workers at
  // once.
  private static class server_task implements Runnable {
    public void run() {
      ZContext ctx = new ZContext();

      // Frontend socket talks to clients over TCP
      Socket frontend = ctx.createSocket(ZMQ.ROUTER);
      frontend.bind("tcp://*:5570");

      // Backend socket talks to workers over inproc
      Socket backend = ctx.createSocket(ZMQ.DEALER);
      backend.bind("inproc://backend");

      // Launch pool of worker threads, precise number is not critical
      for (int threadNbr = 0; threadNbr < 5; threadNbr++)
        new Thread(new server_worker(ctx)).start();

      // Connect backend to frontend via a proxy
      ZMQ.proxy(frontend, backend, null);

      ctx.destroy();
    }
  }

  // Each worker task works on one request at a time and sends a random number
  // of replies back, with random delays between replies:

  private static class server_worker implements Runnable {
    private ZContext ctx;

    public server_worker(ZContext ctx) {
      this.ctx = ctx;
    }

    public void run() {
      Socket worker = ctx.createSocket(ZMQ.DEALER);
      worker.connect("inproc://backend");

      while (!Thread.currentThread().isInterrupted()) {
        // The DEALER socket gives us the address envelope and message
        ZMsg msg = ZMsg.recvMsg(worker);
        ZFrame address = msg.pop();
        ZFrame content = msg.pop();
        assert (content != null);
        msg.destroy();

        // Send 0..4 replies back
        int replies = rand.nextInt(5);
        for (int reply = 0; reply < replies; reply++) {
          // Sleep for some fraction of a second
          try {
            Thread.sleep(rand.nextInt(1000) + 1);
          } catch (InterruptedException e) {
          }
          address.send(worker, ZFrame.REUSE + ZFrame.MORE);
          content.send(worker, ZFrame.REUSE);
        }
        address.destroy();
        content.destroy();
      }
      ctx.destroy();
    }
  }

  // The main thread simply starts several clients, and a server, and then
  // waits for the server to finish.

  public static void main(String[] args) throws Exception {
    ZContext ctx = new ZContext();
    new Thread(new client_task()).start();
    new Thread(new client_task()).start();
    new Thread(new client_task()).start();
    new Thread(new server_task()).start();

    // Run for 5 seconds then quit
    Thread.sleep(5 * 1000);
    ctx.destroy();
  }
}
公共类asyncsrv{
// ---------------------------------------------------------------------
//这是我们的客户任务
//它连接到服务器,然后每秒发送一次请求
//当他们到达时,它收集回应,并打印出来。我们会
//并行运行多个客户端任务,每个任务具有不同的随机ID。
private static Random rand=new Random(System.nanoTime());
私有静态类客户端任务实现可运行{
公开募捐{
ZContext ctx=新的ZContext();
Socket client=ctx.createSocket(ZMQ.DEALER);
//设置随机标识以使跟踪更容易
String identity=String.format(“%04X-%04X”,rand.nextInt(),rand.nextInt());
client.setIdentity(identity.getBytes());
客户端连接(“tcp://localhost:5570");
PollItem[]items=new PollItem[]{new PollItem(client,Poller.POLLIN)};
int requestNbr=0;
而(!Thread.currentThread().isInterrupted()){
//每秒勾选一次,将到达的消息拉入
用于(整数厘=0;厘<100;厘++){
//这一行给出了编译错误,因为它表示未定义
ZMQ.民意测验(项目10);
如果(项[0].isReadable()){
ZMsg msg=ZMsg.recvMsg(客户端);
msg.getLast().print(标识);
msg.destroy();
}
}
client.send(String.format(“request#%d”,++requestNbr),0);
}
ctx.destroy();
}
}
//这是我们的服务器任务。
//它使用多线程服务器模型将请求处理到池中
//一个工人可以处理
//一次一个请求,但一个客户端可以同时与多个工作人员交谈
//一次。
私有静态类服务器\u任务实现可运行{
公开募捐{
ZContext ctx=新的ZContext();
//前端套接字通过TCP与客户端对话
套接字前端=ctx.createSocket(ZMQ.ROUTER);
前端绑定(“tcp://*:5570”);
//后端套接字通过inproc与工人对话
套接字后端=ctx.createSocket(ZMQ.DEALER);
backend.bind(“inproc://backend");
//启动工作线程池,准确的数量并不重要
对于(int threadNbr=0;threadNbr<5;threadNbr++)
新线程(新服务器工作线程(ctx)).start();
//通过代理将后端连接到前端
代理(前端、后端、空);
ctx.destroy();
}
}
//每个辅助任务一次处理一个请求,并发送一个随机数
//回复次数,回复之间随机延迟:
私有静态类服务器\u worker实现可运行{
私人ZContext ctx;
公共服务器\u工作程序(ZContext ctx){
this.ctx=ctx;
}
公开募捐{
插座工人=ctx.createSocket(ZMQ.DEALER);
worker.connect(“inproc://backend");
而(!Thread.currentThread().isInterrupted()){
//经销商插座为我们提供了地址信封和信息
ZMsg msg=ZMsg.recvMsg(工人);
ZFrame address=msg.pop();
ZFrame content=msg.pop();
断言(内容!=null);
msg.destroy();
//返回0..4个回复
int replies=rand.nextInt(5);
for(int reply=0;reply
在0.4.0中没有轮询方法。但是您可以使用
ZPoller

例如:

1-您需要创建轮询器的新实例:

ZPoller zPoller = new ZPoller(ctx);
zPoller.register(client, ZMQ.Poller.POLLIN);
2-投票:

zPoller.poll(10);
3-如果套接字可读,则读取:

if (zPoller.isReadable(client)) {
    ZMsg msg = ZMsg.recvMsg(client);
    msg.getLast().print(identity);
    msg.destroy();
}
因此,您的代码将如下所示:

public class asyncsrv {
    // ---------------------------------------------------------------------
    // This is our client task
    // It connects to the server, and then sends a request once per second
    // It collects responses as they arrive, and it prints them out. We will
    // run several client tasks in parallel, each with a different random ID.
    private static Random rand = new Random(System.nanoTime());

    private static class client_task implements Runnable {

        public void run() {
            ZContext ctx = new ZContext();
            ZMQ.Socket client = ctx.createSocket(ZMQ.DEALER);

            // Set random identity to make tracing easier
            String identity = String.format("%04X-%04X", rand.nextInt(), rand.nextInt());
            client.setIdentity(identity.getBytes());
            client.connect("tcp://localhost:5570");

            //ZMQ.PollItem[] items = new ZMQ.PollItem[] {new ZMQ.PollItem(client, ZMQ.Poller.POLLIN)};
            ZPoller zPoller = new ZPoller(ctx);
            zPoller.register(client, ZMQ.Poller.POLLIN);

            int requestNbr = 0;
            while (!Thread.currentThread().isInterrupted()) {
                // Tick once per second, pulling in arriving messages
                for (int centitick = 0; centitick < 100; centitick++) {
                    // this line is giving compilation error as it says undefined
                    //ZMQ.poll(items, 10);
                    zPoller.poll(10);
                    /*if (items[0].isReadable()) {
                        ZMsg msg = ZMsg.recvMsg(client);
                        msg.getLast().print(identity);
                        msg.destroy();
                    }*/
                    if (zPoller.isReadable(client)) {
                        ZMsg msg = ZMsg.recvMsg(client);
                        msg.getLast().print(identity);
                        msg.destroy();
                    }
                }
                client.send(String.format("request #%d", ++requestNbr), 0);
            }
            ctx.destroy();
        }
    }

    // This is our server task.
    // It uses the multithreaded server model to deal requests out to a pool
    // of workers and route replies back to clients. One worker can handle
    // one request at a time but one client can talk to multiple workers at
    // once.
    private static class server_task implements Runnable {
        public void run() {
            ZContext ctx = new ZContext();

            // Frontend socket talks to clients over TCP
            ZMQ.Socket frontend = ctx.createSocket(ZMQ.ROUTER);
            frontend.bind("tcp://*:5570");

            // Backend socket talks to workers over inproc
            ZMQ.Socket backend = ctx.createSocket(ZMQ.DEALER);
            backend.bind("inproc://backend");

            // Launch pool of worker threads, precise number is not critical
            for (int threadNbr = 0; threadNbr < 5; threadNbr++)
                new Thread(new server_worker(ctx)).start();

            // Connect backend to frontend via a proxy
            ZMQ.proxy(frontend, backend, null);

            ctx.destroy();
        }
    }

    // Each worker task works on one request at a time and sends a random number
    // of replies back, with random delays between replies:

    private static class server_worker implements Runnable {
        private ZContext ctx;

        public server_worker(ZContext ctx) {
            this.ctx = ctx;
        }

        public void run() {
            ZMQ.Socket worker = ctx.createSocket(ZMQ.DEALER);
            worker.connect("inproc://backend");

            while (!Thread.currentThread().isInterrupted()) {
                // The DEALER socket gives us the address envelope and message
                ZMsg msg = ZMsg.recvMsg(worker);
                ZFrame address = msg.pop();
                ZFrame content = msg.pop();
                assert (content != null);
                msg.destroy();

                // Send 0..4 replies back
                int replies = rand.nextInt(5);
                for (int reply = 0; reply < replies; reply++) {
                    // Sleep for some fraction of a second
                    try {
                        Thread.sleep(rand.nextInt(1000) + 1);
                    } catch (InterruptedException e) {
                    }
                    address.send(worker, ZFrame.REUSE + ZFrame.MORE);
                    content.send(worker, ZFrame.REUSE);
                }
                address.destroy();
                content.destroy();
            }
            ctx.destroy();
        }
    }

    // The main thread simply starts several clients, and a server, and then
    // waits for the server to finish.

    public static void main(String[] args) throws Exception {
        ZContext ctx = new ZContext();
        new Thread(new client_task()).start();
        new Thread(new client_task()).start();
        new Thread(new client_task()).start();
        new Thread(new server_task()).start();

        // Run for 5 seconds then quit
        Thread.sleep(5 * 1000);
        ctx.destroy();
    }
}
公共类asyncsrv{
// ---------------------------------------------------------------------
//这是我们的客户任务
//它连接到服务器,然后每秒发送一次请求
//当他们到达时,它收集回应,并打印出来。我们会
//并行运行多个客户端任务,每个任务具有不同的随机ID。
private static Random rand=new Random(System.nanoTime());
私有静态类客户端任务实现可运行{
公开募捐{
ZContext ctx=新的ZContext();
ZMQ.Socket客户端=ctx.createSocket(ZMQ.DEALER);
//设置随机标识以使跟踪更容易
String identity=String.format(“%04X-%04X”,rand.nextInt(),rand.nextInt());
client.setIdentity(identity.getBytes());
客户端连接(“tcp://localhost:5570");
//ZMQ.PollItem[]items=new ZMQ.PollItem[]{new ZMQ.PollItem(客户端,