1

我一直在 F# 交互式会话中尝试一些基本的 HTTP 请求响应操作,以尝试更好地了解该语言。这里的一切似乎都按预期工作,除非当我获得 HTTP 请求的响应流时,我似乎永远无法从中读取任何内容。在下面的代码中,我每次都从 printfn 行获取文本,但 for 的值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
4

1 回答 1

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()
}
于 2013-07-31T04:36:44.253 回答