我试图从 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
Update
问题似乎是 receive(number) 形式需要确切的 number 字节并等待它们。但如果我不知道还剩下多少字节,该怎么办?
(http请求只是一个例子,我指的是从套接字读取字节的通用请求)
卢阿5.1.3
好的,我找到了这个解决方案
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"
缺点是settimeout,因为请求至少需要1秒,任何超过1秒的网络延迟都会导致错误。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)