04
13
F#プログラミングメモ #3
2011.04.13(23:52)
私も同期版と非同期版のHTTPクライアントを書いてみた。洗練はこれから。
実行結果
// FSharp-2.0.0.0
open System.IO;;
open System.Net;;
let getTitle (html : string) =
let startPos = html.IndexOf("<title>")+7 in
let endPos = html.IndexOf("</title>") in
let title = html.Substring(startPos, endPos - startPos) in
title;;
// 同期版
let SyncHttp (url:string) =
let req = WebRequest.Create(url)
#if use_proxy
req.Proxy <- new WebProxy("http://10.0.xx.xx:8080")
#endif
use rsp = req.GetResponse() in
use stream = rsp.GetResponseStream() in
use reader = new StreamReader(stream) in
let html = reader.ReadToEnd() in
getTitle(html) |> printfn "SyncHttp [%s]";;
let pages =
[|
SyncHttp "http://www.google.co.jp/";
SyncHttp "http://news.google.co.jp/nwshp?hl=ja&tab=wn";
SyncHttp "http://www.yahoo.co.jp/";
|];;
// 非同期版
type System.Net.WebRequest with
member x.GetResponseAsync() =
Async.FromBeginEnd(x.BeginGetResponse, x.EndGetResponse)
let AsyncHttp (url:string) =
async { let req = WebRequest.Create(url) in
#if use_proxy
req.Proxy <- new WebProxy("http://10.0.xx.xx:8080")
#endif
let! rsp = req.GetResponseAsync() in
use stream = rsp.GetResponseStream() in
use reader = new StreamReader(stream) in
let html = reader.ReadToEnd() in
getTitle(html) |> printfn "AsyncHttp [%s]"
};;
let Sleeping n =
async { do! Async.Sleep(n)
printfn "timeount %d ms" n
};;
Async.RunSynchronously ( AsyncHttp "http://www.google.com"; )
Async.RunSynchronously ( Async.Parallel [ Sleeping(2000);
AsyncHttp "http://www.google.com";
AsyncHttp "http://news.google.co.jp/nwshp?hl=ja&tab=wn";
AsyncHttp "http://www.yahoo.co.jp/";
Sleeping(1000);
]);;
実行結果
SyncHttp [Google]
SyncHttp [Google ニュース]
SyncHttp [Yahoo! JAPAN]
AsyncHttp [Google]
AsyncHttp [Yahoo! JAPAN]
AsyncHttp [Google ニュース]
AsyncHttp [Google]
timeount 1000 ms
timeount 2000 ms