Created
October 9, 2012 07:37
-
-
Save richardhundt/3857202 to your computer and use it in GitHub Desktop.
http server with keep-alive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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)
end
end)
main:join()