Luke
Luke

Reputation: 2168

NodeMCU HTTP server response length limit

I am running a TCP HTTP server on my NodeMCU. I am serving files, such as HTML, CSS and JavaScript. This was fine until the code started to get long.

What's happening is that the response is just getting cut off. It's happening at about exactly 1024 characters (it seems to be the magic number).

A solution would be to host the files on a server such as Google Drive, Dropbox or Github. However, internet access is not available, because the server is being run through a hotspot created by the NodeMCU.

Any way to override this limit?

Upvotes: 0

Views: 885

Answers (1)

xLarry
xLarry

Reputation: 181

The ESP cannot stream data across multiple IP packets, which is why it gets cropped after 1024 characters.

Here is how I am serving larger files on my ESP running NodeMCU:

responseQueue = {}

function processQueue(socket)
  if #responseQueue > 0 then
    socket:send( table.remove(responseQueue, 1) )
  else
    socket:close()
    collectgarbage()
  end
end

function sendFile(conn, filename)
  if file.open(filename, "r") then
    table.insert(responseQueue, 'HTTP/1.1 200 OK\r\n')
    table.insert(responseQueue, 'Content-Type: text/html\r\n\r\n')

    local lastPos = 0

    repeat
      file.seek("set", lastPos)
      local line = file.read(512)
      file.close()

      if line then
        table.insert(responseQueue, line)
        lastPos = lastPos + 512
      else
        lastPos = nil
      end
    until(line == nil)
  end

  processQueue(conn)
end

Side note: The original answer that was given by @TerryE here pointed me to the above posted implementation.

Upvotes: 1

Related Questions