Hacker News new | ask | show | jobs
by spc476 5810 days ago
Really? I recently wrote a framework to do networking with Lua. The network code itself is event based, but each TCP connection is handled by a Lua coroutine which makes it easy to write straightforward code such as:

  function main(socket)
   io.stdout:write("connection from " .. tostring(socket))
   while(true)
     local cmd = string.upper(socket:read())
     if cmd == "SHOW" then
       socket:write("show me some stuff\n")
     elseif cmd == "PING" then
       for i = 1 , 15 do
         socket:write(".")
         socket:sleep(1)
       end
       socket:write("\n")
     elseif cmd == "QUIT" then
       socket:write("Good bye\n");
       return
     elseif cmd == nil then
       return
     end
   end
  end
Makes writing simple servers nice and easy.
1 comments

Rather than socket:sleep(), you probably want to use socket.select to multiplex IO. (I'm assuming you're using LuaSocket, though that's not entirely clear.)

As with select(2) in general, this doesn't scale up past 100ish idle sockets - it has to do a full scan over all sockets to check which are ready for IO, and the latency eventually dominates. (Not a big deal for most uses, but problematic for web applications.) If that's not an issue, though, it's quite easy. Lua is very underrated, IMHO.

I'm working on a Lua library (octafish) for doing libev + coroutine and/or callback-based servers. It's been on the back burner for a bit, though - a couple other projects have been crowding it out. I'll put it on github once it's further along.

I'm not using LuaSocket but my own homegrown code based off epoll() (it was a learning experience in embedding Lua). It could probably be adapted to libev if I had the interest in doing so.
Ok. What you wrote would adapt to select and nonblocking sockets in LuaSocket pretty easily, FWIW. Using epoll / kqueue (directly or via libev/libevent) scales better, but you're blocking on the sleep, so it wouldn't matter.