开发者

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开发者_如何学Python
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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜