了解路由器的5个REQ

时间:2016-07-14 03:18:57

标签: scala zeromq

查看此5 REQ <--> 1 ROUTER设置的Scala code

工人

 class WorkerTask extends Runnable {
    override def run: Unit = {
      val rand = new Random(System.currentTimeMillis())
      val context = ZMQ.context(1)
      val worker = context.socket(ZMQ.REQ)
      worker.connect("tcp://localhost:5555")
      var total = 0
      var workload = ""

      do {
        worker.send("Ready".getBytes, 0)
        workload = new String(worker.recv(0))
        Thread.sleep (rand.nextInt(1) * 1000)
        total += 1
      } while (workload.equalsIgnoreCase("END") == false)
      printf("Completed: %d tasks\n", total)
    }
  }

main(路由器)

 def main(args: Array[String]): Unit = {
    val NBR_WORKERS = 5
    val context = ZMQ.context(1)
    val client = context.socket(ZMQ.ROUTER)

    assert(client.getType > -1)
    client.bind("tcp://*:5555")
    val workers = List.fill(NBR_WORKERS)(new Thread(new WorkerTask))
    workers.foreach (_.start)

    for (i <- 1 to (NBR_WORKERS * 10)) {
      // LRU worker is next waiting in queue
      val address = client.recv(0)
      val empty = client.recv(0)
      val ready = client.recv(0)

      client.send(address, ZMQ.SNDMORE)
      client.send("".getBytes, ZMQ.SNDMORE)
      client.send("This is the workload".getBytes, 0)
    }

    for (i <- 1 to NBR_WORKERS) {
      val address = client.recv(0)
      val empty = client.recv(0)
      val ready = client.recv(0)

      client.send(address, ZMQ.SNDMORE)
      client.send("".getBytes, ZMQ.SNDMORE)
      client.send("END".getBytes, 0)
    }
  }

在我的机器上运行:

[info] Running net.server.RouterToReq
Completed: 21 tasks
Completed: 1 tasks
Completed: 27 tasks
Completed: 5 tasks
Completed: 1 tasks

由于我部分理解上述代码,5 REQ名工作人员接受来自ROUTER端口5555的请求。

最后,在以下代码中:

 for (i <- 1 to NBR_WORKERS) {
      val address = client.recv(0)
      val empty   = client.recv(0)
      val ready   = client.recv(0)

client,即ROUTER接收了什么消息?

1 个答案:

答案 0 :(得分:1)

工作人员发送消息&#34; Ready&#34;反复作为单帧消息。

REQ套接字将在前面添加一个空白分隔符框架。 ROUTER套接字将在任何收到的消息的前面添加一个标识符框,以标识它来自何处。

因此,单个就绪消息在路由器上收到时会成为3帧消息,这就是需要进行3次recv呼叫的原因。

当您发送路由器套接字时,第一帧将被删除并用于标识要将消息发送到哪个客户端。 REQ套接字将删除所有帧,直到找到空帧,因此您只需要在工作方进行一次recv调用。