Skip to content

Commit 34342f0

Browse files
committed
Add luvit implementations for echo & http servers
Since we are comparing nodejs and its uv bindings, it would be interesting to see how lua's libuv bindings compare.
1 parent d64a46b commit 34342f0

File tree

2 files changed

+50
-0
lines changed

2 files changed

+50
-0
lines changed

servers/luvit_http_server.lua

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
local http = require('http')
2+
local url = require('url')
3+
4+
responses = {}
5+
6+
http.createServer(function (req, res)
7+
req.uri = url.parse(req.url)
8+
local msize = 1024
9+
local path = req.uri.pathname
10+
if string.len(path) > 1 then
11+
msize = tonumber(string.sub(path, 2))
12+
end
13+
14+
if not responses[msize] then
15+
responses[msize] = string.rep("X", msize)
16+
end
17+
18+
res:setHeader("Content-Type", "text/plain")
19+
res:setHeader("Content-Length", msize)
20+
res:finish(responses[msize])
21+
end):listen(25000, '127.0.0.1')
22+
23+
print('Server running at http://127.0.0.1:25000/')

servers/luvitecho.lua

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
local uv = require('uv')
2+
3+
-- Create listener socket
4+
local server = uv.new_tcp()
5+
server:bind('127.0.0.1', 25000)
6+
7+
server:listen(128, function(err)
8+
-- Create socket handle for client
9+
local client = uv.new_tcp()
10+
11+
-- Accept incoming connection
12+
server:accept(client)
13+
14+
-- Relay data back to client
15+
client:read_start(function(err, data)
16+
if err then
17+
client:close()
18+
return
19+
end
20+
21+
if data then
22+
client:write(data)
23+
else
24+
client:close()
25+
end
26+
end)
27+
end)

0 commit comments

Comments
 (0)