0

编辑版主

我今天早上遇到了这个问题,但是问题已经以某种方式自行解决了。如果它回来了,我可以确切地知道发生了什么,我会用更多细节重新提出另一个问题。谢谢

我有以下代码来启动一个 http 监听器(到目前为止我已经从这个系列文章中复制并粘贴了很多)

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 告诉我不存在带有 ths 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 )

感谢您的任何启发...

4

1 回答 1

2

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

于 2013-09-13T10:54:13.250 回答