在讀取 || 傳送大量資料的時候,可以利用 IO::* 這類模組去一次讀取其中一段資料 (Chunk) 就寫入暫存檔 || 送出,來避免對記憶體造成負擔的手法可說相當常用。也是 HTTP Server 用來做 Streaming 或是 Long Polling / Comet 的基礎。
Client 端的用法就沒有那麼絢麗的名字了(開發 Client 的人沒有必要用絢麗的名字震懾老闆?:p)。LWP 對 Chunk 手法也有支援,不過在 GET 和 POST 兩種 HTTP 動做的支援方式分別使用了接受 callback 和利用全域變數啟用的方式,有點不一致,特此紀錄一筆。
GET 使用 Chunk 的方式在 lwpcook 有詳盡記載。在 LWP::UserAgent 物件呼叫 request 方法時多傳入一個 callback 即可。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ua->request( | |
HTTP::Request->new(GET => $URL), | |
sub { | |
my($chunk, $res) = @_; | |
# do something on $chunk | |
} | |
); |
POST 動作其實也應該可以提供 callback。想像起來應該是這樣:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$req = HTTP::Request->new(POST => $URL); | |
$req->header(KEY => VALUE); | |
$req->content($bytes); | |
$ua->request( | |
$req, | |
sub { | |
my($chunk, $socket, $res) = @_; | |
$socket->write($chunk); | |
} | |
); | |
大概是反正多數時候只能寫
$socket->write($chunk)
,所以乾脆就給個全域變數當作開關?
$HTTP::Request::Common::DYNAMIC_FILE_UPLOAD = 1;
雖然有 callback 的話應該還是有點用途的。
No comments:
Post a Comment