luasocket存在问题

我尝试从 lua socket 中读取一些 (二进制) 数据,但上面的代码不会终止循环。我该如何知道流已经结束了?

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"

输出结果为
read
read done
512
read

更新

似乎问题在于 receive(number) 格式需要精确的字节数并等待它们。但如果我不知道还剩下多少字节,该怎么做? (HTTP 请求仅是我提到用于从套接字中读取字节的通用请求的示例)

lua 5.1.3

原文链接 https://stackoverflow.com/questions/5416082

点赞
stackoverflow用户114226
stackoverflow用户114226

我找到了这个解决方案

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"

这个解决方案的缺点是设置了超时时间。因为请求至少需要1秒钟,任何超过1秒钟的网络延迟都会导致错误。

2011-03-24 10:30:36