lua zmq client

该博客介绍了如何在Lua中使用lzmq库创建ZMQ客户端,包括PULL模式的接收器,用于从服务器接收批量任务;REQ模式的请求者,向服务器发送请求并接收响应;以及SUB模式的订阅者,订阅并处理来自服务器的天气更新消息。示例代码展示了如何进行连接、发送、接收和处理不同模式下的消息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

require "zhelpers"
local zmq = require "lzmq"

---------------------------PULL--------------------

local ztimer = require "lzmq.timer"

local context = zmq.context()
local receiver,err = context:socket{zmq.PULL,bind = "tcp://*:5558"}
zassert(receiver, err)

-- Wait for start of batch
-- receiver:recv()

-- Start our clock now
local timer = ztimer.monotonic():start()
print("111111111")
-- Process 100 confirmations
for task_nbr = 1, 10 do
print("22222222")
local message = receiver:recv();
if task_nbr % 10 == 0 then
    print(task_nbr)
    print(message)
else
   print (task_nbr)
end
io.flush()
end

-- Calculate and report duration of batch
printf ("Total elapsed time: %d msec\n", timer:stop());

-----------------------------REQ-------------------

print("Connecting to hello world server ...")
local context = zmq.context()
local requester, err = context:socket{zmq.REQ, 
  connect = "tcp://localhost:5555"
}
zassert(requester, err)

for request_nbr = 0, 9 do
  print ("Sending Hello " .. request_nbr .. "...")
  requester:send("Hello")
  local buffer = requester:recv()
  print("Received World " .. request_nbr)
end

----------------------------SUB-------------------

--SUB会过滤PUB来得消息,由filter来定义数据格式
local filter =""
printf("Collecting updates from weather server ...\n")
local context = zmq.context()
local subscriber, err = context:socket{zmq.SUB,
  subscribe = filter;
  -- connect   = "tcp://172.15.2.4:6000";
  connect = "tcp://localhost:5554";
}
zassert(subscriber,err)
print(subscriber)
local update_nbr, total_temp = 100, 0
-- for i = 1, update_nbr do
while(1) do
print("~~~~~~~~~~~")
local message = subscriber:recv()
-- local y = {}
-- y = string.split(message,%s)
-- print(y..":"..#y)
local x = ""
local table1 = {}
for name1 in string.gmatch(message,"([%d]*)%s+([-]?[%d-]*)%s+([-]?[%d-]*)") do 
table.insert(table1.name1)
print(name1)
end
for i=1,7 do
-- x = x..table1[i]..","
print(i)
print(table1[i])
end
-- for name2 in string.gmatch(message,"title_name %w+") do 
-- print(name2)
-- x = x..","..name2
-- end
print(x)
print(total_temp.."-> "..message)
total_temp = total_temp + 1
end
-- printf ("Average temperature for zipcode '%s' was %dF\n",
--   filter, (total_temp / update_nbr))



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值