套接字 – luasocket的问题

我试图从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

更新

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

lua 5.1.3

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

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秒将导致错误.

点赞