Skip to content

Instantly share code, notes, and snippets.

@zhaozg
Created October 11, 2014 07:58
Show Gist options
  • Save zhaozg/0789754eb36ac1deeeb0 to your computer and use it in GitHub Desktop.
Save zhaozg/0789754eb36ac1deeeb0 to your computer and use it in GitHub Desktop.
luv_test_srv.lua
local uv = require'luv'
local os, string = os, string
local print = print
io.read()
local host = arg[1] or '127.0.0.1'
local port = arg[2] and tonumber(arg[2]) or 8080
local bps, concurrent, count, total_bytes = 0, 0, 0, 0
--- timer ---
local loop = 0
uv.timer_start(uv.new_timer(), 1000, 1000, function (timer)
if loop%20 == 0 then
print(' DATA TIME BPS CONCURRENT COUNT SPEED(M)')
end
print(string.format('%s % 8d % 8d % 8d %02f',os.date(),bps, concurrent, count, total_bytes/(1024*1024)) )
bps = 0
total_bytes = 0
collectgarbage()
loop = loop + 1
end)
--- server ---
local function create_server(host, port, on_connection)
local server = uv.new_tcp()
uv.tcp_bind(server, host, port)
uv.listen(server, 511, function(self)
local client = uv.new_tcp()
uv.accept(server, client)
bps = bps + 1
concurrent = concurrent + 1
count = count + 1
on_connection(client)
end)
return server
end
local server = create_server(host, port, function (client)
uv.read_start(client, function (self, err, chunk)
if err then
print(err)
assert(client==self)
uv.close(self)
concurrent = concurrent - 1
else
if chunk and #chunk>0 then
total_bytes = total_bytes + #chunk
uv.write(self, chunk)
else
uv.close(self)
concurrent = concurrent - 1
end
end
end)
end)
--------------------------------------------
uv.run()
print("done")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment