从WebResponse Response Stream读取响应

时间:2013-07-31 03:58:50

标签: http f# stream

我在F#交互式会话中一直在玩一些基本的HTTP请求响应操作,以尝试更好地理解该语言。这里的所有内容似乎都按预期工作,除非我获得HTTP请求的响应流,我似乎永远无法读取任何内容。在下面的代码中,我每次都从printfn行获取文本,但responseString的值似乎总是为空。我错过了什么明显的东西吗?

let httpListener = new HttpListener()
httpListener.Prefixes.Add("http://*:8020/")

let getContext = Async.FromBeginEnd(httpListener.BeginGetContext, httpListener.EndGetContext)

let processRequest = async {
    while true do
        let! context = getContext
        let request = context.Request
        use requestReader = new StreamReader(request.InputStream)
        let requestString = requestReader.ReadToEnd()
        let response = context.Response
        use streamWriter = new StreamWriter(response.OutputStream)
        streamWriter.WriteLine "A response!"
        response.Close()
}

httpListener.Start()

let maxThreads = 10
for n = 0 to maxThreads do
    Async.Start processRequest

printfn "HttpListener started with %d maximum threads processing requests." maxThreads

let sendRequest = async {
    let request = WebRequest.Create("http://localhost:8020") :?> HttpWebRequest
    let postBytes = Encoding.ASCII.GetBytes("Issuing HTTP")
    request.Method <- "POST"
    request.ContentType <- "application/x-www-form-urlencoded"
    request.ContentLength <- int64 postBytes.Length
    let requestStream = request.GetRequestStream()
    requestStream.Write(postBytes, 0, postBytes.Length)
    requestStream.Close()

    let! response = Async.FromBeginEnd(request.BeginGetResponse, request.EndGetResponse)
    let responseStream = response.GetResponseStream()
    use streamReader = new StreamReader(responseStream)
    let responseString = streamReader.ReadToEnd()

    printfn "Received the following response: %s" responseString
}

for n = 0 to maxThreads do
    Async.Start sendRequest

1 个答案:

答案 0 :(得分:1)

您需要减少StreamWriter的使用范围,以便可以在Dispose上刷新。

let processRequest = async {
    while true do
        let! context = getContext
        let request = context.Request
        use requestReader = new StreamReader(request.InputStream)
        let requestString = requestReader.ReadToEnd()
        let response = context.Response
        do
            use streamWriter = new StreamWriter(response.OutputStream)
            streamWriter.WriteLine "A response!"
        response.Close()
}