查看此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)
}
}
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
接收了什么消息?
答案 0 :(得分:1)
工作人员发送消息&#34; Ready&#34;反复作为单帧消息。
REQ
套接字将在前面添加一个空白分隔符框架。
ROUTER
套接字将在任何收到的消息的前面添加一个标识符框,以标识它来自何处。
因此,单个就绪消息在路由器上收到时会成为3帧消息,这就是需要进行3次recv
呼叫的原因。
当您发送路由器套接字时,第一帧将被删除并用于标识要将消息发送到哪个客户端。 REQ
套接字将删除所有帧,直到找到空帧,因此您只需要在工作方进行一次recv
调用。