title: LuaSocket server:accept() timeout (TCP)
body: <p><strong>Problem</strong></p>
  
  <p>Following <code>LuaSocket</code> <a href="http://w3.impa.br/~diego/software/luasocket/introduction.html" rel="noreferrer">Introduction</a> I managed to get the server running. I also managed to connect from the client side. I noticed, however, that the server script freezes until <code>server:accept()</code> gets the connection.</p>
  
  <p><strong>Research</strong></p>
  
  <p><code>LuaSocket</code> <a href="http://w3.impa.br/~diego/software/luasocket/tcp.html#settimeout" rel="noreferrer">Reference</a> specifies:</p>
  
  <blockquote>
    <p>Use the settimeout method or accept might block until another client shows up.</p>
  </blockquote>
  
  <p>This is even included in the example code. However, <code>client:settimeout(10)</code> is called after <code>local client = server:accept()</code> so the script gets blocked before it reaches this point.</p>
  
  <p>I read that this could be worked around by multithreading but this seems to be an exaggeration.</p>
  
  <p><strong>Questions</strong></p>
  
  <ol>
  <li>How do you cause the server script to stop waiting for connection and move on?</li>
  <li>How do I guard from similar problems with <code>client:receive()</code> (server side) and <code>tcp:receive()</code> (client side) (or <code>client:settimeout(10)</code> takes care of that)?</li>
  </ol>
  
  <p><strong>Code</strong></p>
  
  <p>server (from <code>LuaSocket</code> <a href="http://w3.impa.br/~diego/software/luasocket/introduction.html" rel="noreferrer">Introduction</a>)</p>
  
  <pre><code>-- load namespace
  local socket = require("socket")
  -- create a TCP socket and bind it to the local host, at any port
  local server = assert(socket.bind("*", 0))
  -- find out which port the OS chose for us
  local ip, port = server:getsockname()
  -- print a message informing what's up
  print("Please telnet to localhost on port " .. port)
  print("After connecting, you have 10s to enter a line to be echoed")
  -- loop forever waiting for clients
  while 1 do
    -- wait for a connection from any client
    local client = server:accept()
    -- make sure we don't block waiting for this client's line
    client:settimeout(10)
    -- receive the line
    local line, err = client:receive()
    -- if there was no error, send it back to the client
    if not err then client:send(line .. "\n") end
    -- done with client, close the object
    client:close()
  end
  </code></pre>
  
  <p>client (follows <a href="https://stackoverflow.com/a/9014261/6575359">this answer</a>)</p>
  
  <pre><code>local host, port = "127.0.0.1", 100
  local socket = require("socket")
  local tcp = assert(socket.tcp())
  
  tcp:connect(host, port);
  --note the newline below
  tcp:send("hello world\n");
  
  while true do
      local s, status, partial = tcp:receive()
      print(s or partial)
      if status == "closed" then break end
  end
  tcp:close()
  </code></pre>