Lua sockets - Asynchronous Events

前端 未结 4 627
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-16 19:46

In current lua sockets implementation, I see that we have to install a timer that calls back periodically so that we check in a non blocking API to see if we have received a

4条回答
  •  太阳男子
    2020-12-16 20:38

    I use lua-ev https://github.com/brimworks/lua-ev for all IO-multiplexing stuff. It is very easy to use fits into Lua (and its function) like a charm. It is either select/poll/epoll or kqueue based and performs very good too.

     local ev = require'ev'
     local loop = ev.Loop.default
     local udp_sock -- your udp socket instance
     udp_sock:settimeout(0) -- make non blocking
     local udp_receive_io = ev.IO.new(function(io,loop)
           local chunk,err = udp_sock:receive(4096)
           if chunk and not err then
               -- process data
           end
        end,udp_sock:getfd(),ev.READ)
    
     udp_receive_io:start(loop) 
     loop:loop() -- blocks forever
    

    In my opinion Lua+luasocket+lua-ev is just a dream team for building efficient and robust networking applications (for embedded devices/environments). There are more powerful tools out there! But if your resources are limited, Lua is a good choice!

提交回复
热议问题