(Last Updated: August 1, 2020)

Socket settimeout times out every time for no apparent reason

  • In the pseudo code below settimeout always times out after ten seconds. I can set the timeout to any value and it always times out when it reaches the set value. But why? The transmit is fine and the data is rx'ed OK exactly as expected. ie the expected data is always the length expected. There are no partial results.

    The only way to get it to work is to set the timeout to zero. ie no timeout delay and use socket.select to become a defacto timeout. It works great after that.

    -- Socket library version is: LuaSocket 3.0-rc1
    m_tcp = socket.tcp()
    m_tcp:settimeout(10)    -- set to zero when using socket.select fix 
    m_tcp:connect('ip_address', port)
        -- send request
        local txMsg('Data request. Hi what is the hardware status? (ongoing)')
        -- THIS fixs the problem as long as m_tcp:settimeout() is set to zero
        -- Wait on the socket for 50 msec for rx data.
        -- The rx data will arrive in the rx buffer in less than this time.
        -- *** local rxlist, _, selectStatus = socket.select ({m_tcp}, nil, 0.05)
        -- get the response to the request
        -- get the 16 byte data header, that contains the length of the payload
        local expectedLength = 16
        local s, status, partial = m_tcp:receive(expectedLength)
        if (status == "timeout") then print('timeout') end
        -- the returned data amount varies but we know what it is from the header just rx'ed
        expectedLength = s[1]
        s, status, partial = m_tcp:receive(expectedLength)
        -- do this every 0.5 sec;
        -- we're regularly updating the status of a hardware device
    until false

  • Hi a-lurker,

    This is a pesty problem with the LuaSocket lib that has been fixed years ago, but for some reason is not in the latest GA packages. The problem is in buffer.c, the timeout is only handled correctly if it is compiled with debug flags. Look at about line 80, and if that shows a compiler flag it will have the problem you see. You can install the luarocks scm-2 version and it should work as expected. I have the running with openLuup without any problems.

    Cheers Rene

Log in to reply