2011-03-24 24 views
4

我試圖從一個lua套接字讀取一些(二進制)數據,但上面的代碼不會終止重複循環。我如何知道流的結束已達到?問題與luasocket

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

回答

2

好,我已發現此解決方案

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秒都會導致錯誤。

+0

if line then client:send(line)end if rest then client:send(rest)end that looks not right .... – daurnimator 2011-03-25 00:20:40

+0

它可能是明確的** if line〜= nil then ** ,但沒有區別 – PeterMmm 2011-03-25 07:47:46

+0

我的意思是整個概念......對於HTTP連接,你爲什麼要把你收到的線路發回給他們? – daurnimator 2011-03-29 00:49:24