NGINX LUA 边下载边发送文件内容

用NGINX做WEB服务器, LUA去下载文件,并发送给客户端。

里面用到 curl.so 动态库

package.path = '/usr/local/share/lua/5.1/?.lua;/usr/local/openresty/lualib/resty/?.lua;'
package.cpath = '/usr/local/lib/lua/5.1/?.so;'

require("curl")


function build_w_cb(f)
   return function(s,len)
         ngx.print(s)
         ngx.flush(true)
	  --local wlen = f:write(s)
	  --if (wlen ~= len) then
	--	return len,"writeError"
	 -- else
		return len,nil
	--  end
   end
end

file = io.open("/usr/local/openresty/nginx/html/me.ts", "w")
if (file == nil) then
    ngx.say ("Create File error")
	return
end
ngx.header["Transfer-Encoding"] = 'chunked';
--Transfer-Encoding: chunked
--download XML File
xmlURL = "http://192.168.1.102/pxx/f1.ts"
c = curl.easy_init() 
c:setopt(curl.OPT_URL, xmlURL)
c:setopt(curl.OPT_WRITEFUNCTION, build_w_cb(file))
c:setopt(curl.OPT_FOLLOWLOCATION, 1)

c:setopt(curl.OPT_USERAGENT, "ContentPreload-agent/1.0")
c:setopt(curl.OPT_COOKIEFILE, "./curlpost.cookie")
c:setopt(curl.OPT_CONNECTTIMEOUT, 5)
c:setopt(curl.OPT_TIMEOUT, 3000)
c:setopt(curl.OPT_NOSIGNAL, 1)

ret,strerr = c:perform()

file:close()


这个例子能运行,不过有点不正常的是,文件下载过程中虽然调用 ngx.print  和  ngx.flush , 但是nginx会把内容全部堆积到内存, 文件完毕后才会真正发送给客户端。

这点让我很郁闷,原因应该是因为下载和发送为同一个线程, 只有curl的 perform函数执行完毕后,才会真正发送出去, 在perform函数执行的过程中,虽然调用了print函数,但是该函数只是把内容放到了内存, 无法真正执行 send 函数, 所以数据会堆积到内存。






介绍一下自己的LUA封装 1: C++中的类可以注册到LUA 中,在LUA里面可以使用像C++一样使用对象调用函数一样 2: 将C或者C++中的函数注册到LUA中,在LUA里面直接调用全局函数 3: 加载LUA文件并且执行,执行LUA文件中的某个函数。 会自动平衡LUA堆栈,使用的时候不需要担心LUA栈的问题 4: 可以将LUA中的某个函数作为回调函数,当条件满足时调用回调函数 .................. 这篇就介绍一下怎样在LUA中使用C++的类对象 //说明一下::带有LRT_ 的函数都是自己封装的,在LUA 库里面是没有的 --下面是main 函数 int _tmain(int argc, _TCHAR* argv[]) { //获取LUA 运行状态 lua_State *l = LRT_GetLuaState(); //注册C++类 RegisterLuaClass::RegisterClass(l); char current_dir[260] = {0}; DWORD ret = GetCurrentDirectory(260, current_dir); std::string strTmp(current_dir); std::stringstream strS; strS<<strTmp<<"\\LuaClassTest.lua"; //加载一个LUA文件,只是加载了,并没有执行,一定要返回成功了才可以 LRT_RunChunk if (LRT_ErrorCode_Success == LRT_CreateChunkFromFile(l,strS.str().c_str())) { LRT_RunChunk(l); } strS.clear(); strS.str(""); strS<<strTmp<<"\\dataStruct.lua"; if (LRT_ErrorCode_Success == LRT_CreateChunkFromFile(l,strS.str().c_str())) { LRT_RunChunk(l); } getchar(); return 0; } --下面是LUA文件中代码 --获取C++对象,参数为 类型的名称,这个名称和C++的名称对应 local object = LRTGetObject("Test.Lua.Class") --调用对象的函数 object:Fun1() object:Fun2()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

langeldep

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值