luasocket问题 [英] Problem with luasocket

查看:218
本文介绍了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\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请求只是一个示例,我引用的是从套接字读取字节的通用请求)

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

lua 5.1.3

推荐答案

好,我已经找到了解决方法

Ok, i have found this solution

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

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天全站免登陆