Search code examples
socketslualuasocket

socket send throws timeout error


I have a proxy client between two servers. The main server S1 is on the internet. The proxy client and the second server S2 sit in the same intranet. I have the following code (parts left out for simplicity) which is responsible for forwarding data coming from S2 'as is' to S1:

fsctimeout = 0.01

function send_data(sock, data, i, l)
    local p,err,q = sock:send(data, i, l)
    if(err == "timeout" and q ~= l) then
        fsctimeout = fsctimeout * 2
        sock:settimeout(fsctimeout)
        send_data(sock, data, q + 1, l)
        fsctimeout = fsctimeout / 2
        sock:settimeout(fsctimeout)
    end
end

while not e do

rect, _, st = socket.select({csc, fsc}, nil, .01) --csc is S1, fsc is S2 sockets.

    if(rect[fsc] ~= nil and csc ~= nil) then
        local data, err, part = fsc:receive(8192)
        if(data ~= nil) then
            send_data(csc, data, 1, data:len())
            totalBytesFromFP = totalBytesFromFP + data:len()
        end
        if(part ~= nil) then
            send_data(csc, part, 1, part:len())
            totalBytesFromFP = totalBytesFromFP + part:len()
        end
    end
 end

I wrote the send_data function so that if a send timeouts, it will double the socket timeout and try again. But now sometimes the programs gets stuck inside the send_data function without being successful in sending data. What can I do here? (I am testing trying to send a 1MB file, for small amounts of data this problem doesn't seem to be happenning.)


Solution

  • You change timeout for the first time only after you get "timeout" error, but it never happens because by default send is blocking (so it will never times out).

    Just add csc:settimeout(fsctimeout) before your loop.