luasocket 的问题 [英] Problem with luasocket

查看:18
本文介绍了luasocket 的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 lua 套接字读取一些(二进制)数据,但上述代码并未终止重复循环.我怎么知道流已经结束?

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

")
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 请求只是一个例子,我指的是从套接字读取字节的通用请求)

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

")
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 秒的网络延迟都会导致错误.

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.

这篇关于luasocket 的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆