local zmq = require "lzmq"
-----------------------------PUSH------------------------
local context = zmq.context()
-- Socket to send messages on
local sender, err = context:socket{zmq.PUSH, bind = "tcp://*:5557"}
zassert(sender, err)
-- Socket to send start of batch message on
local sink, err = context:socket{zmq.PUSH, connect = "tcp://localhost:5558"}
zassert(sink, err)
printf("Press Enter when the workers are ready:\n ")
-- getchar()
printf("Sending tasks to workers...\n")
-- The first message is "0" and signals start of batch
-- sink:send("0")
-- Send 10 tasks
local total_msec = 0; -- Total expected cost in msecs
for task_nbr = 1, 10 do
print("xxxxxxxxxxxxxxxxxxxxxxxx")
-- Random workload from 1 to 100msecs
local workload = randof (100) + 1;
local total_msec = total_msec + workload;
sink:send(workload)
print(task_nbr.."=".. workload)
end
printf ("\nTotal expected cost: %d msec\n", total_msec)
-----------------------------REP接受响应模式-----------------
--先要接收一个由REQ来的信息,然后做出响应的操作,返回“响应值”
--严格的按照一个recv一个send,循环下去
local context = zmq.context()
local responder, err = context:socket{zmq.REP, bind = "tcp://*:5555"}
--responder:bind("ipc://weather.ipc")
zassert(responder, err)
while true do
local buffer = zassert(responder:recv())
print("Received " .. buffer)
sleep (1) -- Do some 'work'
zassert(responder:send("World"))
end
-----------------------------PUB--------------
--一直发,由SUB做选择,过滤。如果没有SUB连接则drop发送的消息
local context = zmq.context()
local publisher, err = context:socket{zmq.PUB, bind = "tcp://*:5554"}
zassert(publisher, err)
local y = 0
while true do
local x = "This is a zmq test!"
y = y + 1
sleep(1)
zassert(publisher:send(x))
print(y..":"..x)
end