luasocket的问题

时间:2011-03-24 07:35:10

标签: sockets lua

我正在尝试从lua套接字读取一些(二进制)数据,但上面的代码不会终止重复循环。我怎么知道流的末尾已到达?

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

更新

似乎问题是receive(number)表单需要精确的数字字节并等待它们。但如果我不知道剩下多少字节,该怎么做? (http请求只是一个例子,我指的是从套接字读取字节的通用请求)

lua 5.1.3

1 个答案:

答案 0 :(得分:2)

好的,我找到了这个解决方案

client = 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"

缺点是settimeout,因为请求至少需要1秒,任何网络延迟超过1秒都会导致错误。