请教如何在thread中正确关闭通过参数传进来的cosocket连接(stream-lua-nginx-module)

90 views
Skip to first unread message

nacoz

unread,
Jan 13, 2017, 12:50:15 AM1/13/17
to openresty
为了实现类似 nodejs 的 pipe 功能,stream-lua-nginx-module 打了https://github.com/openresty/stream-lua-nginx-module/pull/33补丁。

pipe()函数中的dst:close()调用了,但貌似没有生效,在15秒后srvsock依然会报 tcp socket read timed out 错误。跪求大神指点!!!

代码摘要如下:


local spawn = ngx.thread.spawn
local wait  = ngx.thread.wait

local function pipe(src, dst, phase)
    while true do
        local data, err, partial = src:receive("*b")
        if not data then
            if partial then
                dst:send(partial)
            end

            if err ~= "closed" then
              --
            else
                -- 调用无效
                dst:close()
                ngx.log(ngx.ERR, "close dst by <", phase, ">")
            end

            break
        end

        local ok, err = dst:send(data)
        if err then
            break
        end
    end
end

local reqsock = assert(ngx.req.socket(true))

local dst = parseRequest(reqsock)

local srvsock = ngx.socket.tcp()
local ok, err = srvsock:connect(dst.host, dst.port)
if not ok then
    return
end

reqsock:settimeout(15000)
srvsock:settimeout(15000)

wait(spawn(pipe, reqsock, srvsock, 'proxy-request'))
wait(spawn(pipe, srvsock, reqsock, 'proxy-response'))

if srvsock ~= nil then
    local ok, err = srvsock:close()
    ngx.log(ngx.ERR, "close srvsock")
    if not ok then
        --
    end
end

if reqsock ~= nil and reqsock.close ~= nil then
    local ok, err = reqsock:close()
    ngx.log(ngx.ERR, "close reqsock")
    if not ok then
        --
    end
end

Reply all
Reply to author
Forward
0 new messages