Skip to content

Instantly share code, notes, and snippets.

@richardhundt
Created October 9, 2012 07:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save richardhundt/3857202 to your computer and use it in GitHub Desktop.
Save richardhundt/3857202 to your computer and use it in GitHub Desktop.
http server with keep-alive
ocal luv = require('luv')
local response_html = "<p>Hello, world!</p>"
local response_size = #response_html
local http_response = "HTTP/1.0 200 OK\r\
Content-Type: text/html\r\
Content-Length: "..tostring(response_size).."\r\
Connection: Keep-Alive\r\
\r\
"..response_html
local server = luv.net.tcp()
server:bind("127.0.0.1", 8080)
server:listen(1024)
local main = luv.fiber.create(function()
while true do
local client = luv.net.tcp()
server:accept(client)
print("accept:", client)
local child = luv.fiber.create(function(client)
print("enter child")
while true do
local got, str = client:read()
if got then
if got == 0 then
print("got zero, EOF?")
else
if client:write(http_response) == -1 then
client:close()
end
end
else
print("got nil, closing")
client:close()
break
end
end
end, client)
-- put it in the ready queue
child:ready()
end
end)
main:join()
@miko
Copy link

miko commented Oct 9, 2012

With timer added:

local luv = require('luv')

local response_html = "

Hello, world!

"
local response_size = #response_html
local http_response = "HTTP/1.0 200 OK\r
Content-Type: text/html\r
Content-Length: "..tostring(response_size).."\r
Connection: Keep-Alive\r
\r
"..response_html

local server = luv.net.tcp()
server:bind("127.0.0.1", 8080)
server:listen(1024)

local main = luv.fiber.create(function()
while true do
local client = luv.net.tcp()
server:accept(client)
print("accept:", client)

  local child = luv.fiber.create(function(client)
     print("enter child")
     local t1 = luv.timer.create()
     t1:start(100,100)
     while true do
        local got, str = client:read()
        if got then
           if got == 0 then
              print("got zero, EOF?", #str, str)
           else
              t1:wait()
              if client:write(http_response) == -1 then
                 client:close()
              end
           end
        else
           print("got nil, closing")
           client:close()
           break
        end
     end
     t1:stop()
  end, client)

  -- put it in the ready queue
  child:ready()

end
end)

main:join()

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment