我的http监听器正在一个控制台项目中工作但不在我的测试中

时间:2013-09-13 07:34:27

标签: f#

主持人的编辑

今天早上我遇到了这个问题,但问题已经以某种方式解决了。如果它回来了,我可以准确地告诉我发生了什么,我将重新打开另一个问题并提供更多细节。 THX

我有以下代码来启动一个http监听器(到目前为止,我已经从this series of article复制并粘贴了很多)

httpAgent.fs

namespace Server.Core

open System.Net
open System.Threading

type Agent<'T> = MailboxProcessor<'T>

/// HttpAgent that listens for HTTP requests and handles
/// them using the function provided to the Start method
type HttpAgent private (url, f) as this =
  let tokenSource = new CancellationTokenSource()
  let agent = Agent.Start((fun _ -> f this), tokenSource.Token)
  let server = async { 
    use listener = new HttpListener()
    listener.Prefixes.Add(url)
    listener.Start()
    while true do 
      let! context = listener.AsyncGetContext()
      agent.Post(context) }
  do Async.Start(server, cancellationToken = tokenSource.Token)

  /// Asynchronously waits for the next incomming HTTP request
  /// The method should only be used from the body of the agent
  member x.Receive(?timeout) = agent.Receive(?timeout = timeout)

  /// Stops the HTTP server and releases the TCP connection
  member x.Stop() = tokenSource.Cancel()

  /// Starts new HTTP server on the specified URL. The specified
  /// function represents computation running inside the agent.
  static member Start(url, f) = 
    new HttpAgent(url, f)

httpServer.fs

module httpServer

open Server.Core


let execute = fun ( server : HttpAgent) -> async {
        while true do 
                let! ctx = server.Receive()
                ctx.Response.Reply(ctx.Request.InputString) }

此代码在控制台项目中运行良好(即:我可以使用浏览器访问它,它确实可以找到它):

[<EntryPoint>]
let main argv = 

    let siteRoot = @"D:\Projects\flaming-octo-spice\src\Site"

    let url = "http://localhost:8082/"
    let server = HttpAgent.Start(url, httpServer.execute)

    printfn "%A" argv
    let s = Console.ReadLine()
    // Stop the HTTP server and release the port 8082
    server.Stop()
    0 // return an integer exit code

而在我的测试中,我无法访问服务器。我甚至设置了一些断点,以便检查服务器是否启动并运行我的浏览器,但chrome告诉我没有主机存在该URL。

namespace UnitTestProject1

open System
open Microsoft.VisualStudio.TestTools.UnitTesting
open Server.Core
open System.Net.Http

[<TestClass>]
type HttpServerTests() = 
    [<TestMethod>]
    member x.Should_start_a_web_site_with_host_address () = 
        let host = "http://localhost:8082/"

        let server = HttpAgent.Start(host, httpServer.execute)

        let url = "http://localhost:8082/test/url"
        let client = new HttpClient()

        let response = client.GetAsync(url)

        Assert.IsTrue(response.Result.IsSuccessStatusCode )

感谢任何启发......

1 个答案:

答案 0 :(得分:2)

您正在端口 8092 启动服务器,但客户端尝试通过 8082 访问它。