PeterMmm
PeterMmm

Reputation: 24630

Problem with luasocket

I'm trying to read some (binary) data from a lua socket, but the above code do not terminate the repeat-loop. How can i know that the end of stream has reached ?

client = require("socket")
client = socket.connect("www.google.com",80)
client:send("GET / HTTP/1.1\n\n")
repeat
  print "read"
  line = client:receive(512)
  print "read done"
  print(#line)
until line==""

print "all done"

Output is
read
read done
512
read

Update

It seems to be the problem that the receive(number) form expects exact number bytes and wait for them. But if i don't know how many bytes are left, how to do that ? (the http request is only an example i refer to a generic request to read bytes from a socket)

lua 5.1.3

Upvotes: 4

Views: 3072

Answers (1)

PeterMmm
PeterMmm

Reputation: 24630

Ok, I have found this solution

local socket = require("socket")
client = socket.connect("www.google.com",80)
client:send("GET / HTTP/1.1\n\n")
client:settimeout(1)
repeat
  print "read"
  line,err,rest = client:receive(512)
  print "read done"
  if line then print(line) end
  if rest then print(rest) end
until err

print "all done"

The drawback is the settimeout, because the request will take at least 1 second and any network delay more than 1 sec will result in an error.

Upvotes: 2

Related Questions