Skip to content

Instantly share code, notes, and snippets.

@yihuang
Created December 26, 2017 06:11
Show Gist options
  • Select an option

  • Save yihuang/7f8d2be038db5636dde35bde6d344865 to your computer and use it in GitHub Desktop.

Select an option

Save yihuang/7f8d2be038db5636dde35bde6d344865 to your computer and use it in GitHub Desktop.
lua curl multi api work with libuv.
local uv = require_uv()
-- run uv event loop in engine loop.
return RunLoop.schedule(function()
uv.run('nowait')
end, 0.02, 0.02)
local multi = curl.multi()
local function check_info()
while true do
local easy, done = multi:info_read(true)
if easy and done then
print('finish', easy:getinfo(curl.INFO_RESPONSE_CODE))
else
break
end
end
end
local fdmap = {}
multi:setopt_socketfunction(function(handler, fd, action)
local poll = fdmap[fd]
if not poll then
poll = uv.new_socket_poll(fd)
fdmap[fd] = poll
end
if action == curl.POLL_REMOVE then
if poll then
fdmap[fd] = nil
poll:stop()
end
else
local events = ''
if action ~= curl.POLL_IN or action == curl.POLL_INOUT then
events = 'r'
end
if action == curl.POLL_OUT or action == curl.POLL_INOUT then
events = events .. 'w'
end
if events ~= '' then
poll:start(events, function(status, evt)
local flags = 0
if evt == 'r' then
flags = curl.CSELECT_IN
elseif evt == 'w' then
flags = curl.CSELECT_OUT
elseif evt == 'rw' then
flags = bit.bor(curl.CSELECT_IN, curl.CSELECT_OUT)
end
multi:socket_action(fd, flags)
check_info()
end)
end
end
return 0
end)
local timer = uv.new_timer()
multi:setopt_timerfunction(function(timeout)
if timeout < 0 then
timer:stop()
else
timer:start(timeout, 0, function()
multi:socket_action(curl.SOCKET_TIMEOUT)
check_info()
end)
end
end)
local easy = curl.easy()
easy:setopt_url('http://www.baidu.com')
easy:setopt_writefunction(function(buf)
print('recv', #buf)
end)
multi:add_handle(easy)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment