使TcpListener异步处理连接的正确方法是什么?

时间:2013-03-07 13:19:51

标签: asynchronous f# async-await tcplistener

对不起,很长的帖子。我想使用TcpListener侦听端口,处理不同(后台)线程中传入连接请求的繁重工作,然后在响应准备就绪时将响应发送回客户端。我在MSDN上阅读了很多代码和示例,并为服务器提出了以下实现。

对于以下所有实现,请假设以下变量:

let sva = "127.0.0.1"
let dspt = 32000

let respondToQuery (ns_ : NetworkStream) (bta_ : byte array) : unit =
    // DO HEAVY LIFTING
    ()

实施1 (普通,同步服务器;我对the code from this MSDN page的翻译)

let runSync () : unit =
    printfn "Entering runSync ()"
    let (laddr : IPAddress) = IPAddress.Parse sva
    let (svr : TcpListener) = new TcpListener (laddr, dspt)
    try
        svr.Start ()
        let (bta : byte array) = Array.zeroCreate<byte> imbs
        while true do
            printfn "Listening on port %d at %s" dspt sva
            let (cl : TcpClient) = svr.AcceptTcpClient ()
            let (ns : NetworkStream) = cl.GetStream ()
            respondToQuery ns bta
            cl.Close ()
        svr.Stop ()
        printfn "Exiting runSync () normally"
    with
        | excp ->
            printfn "Error:  %s" excp.Message
            printfn "Exiting runSync () with error"

实施2 (我对代码on this MSDN page的翻译)

let runAsyncBE () : unit =
    printfn "Entering runAsyncBE ()"
    let (tcc : ManualResetEvent) = new ManualResetEvent (false)
    let (bta : byte array) = Array.zeroCreate<byte> imbs
    let datcc (ar2_ : IAsyncResult) : unit =
        let tcpl2 = ar2_.AsyncState :?> TcpListener
        let tcpc2 = tcpl2.EndAcceptTcpClient ar2_
        let (ns2 : NetworkStream) = tcpc2.GetStream ()
        respondToQuery ns2 bta
        tcpc2.Close ()
        tcc.Set () |> ignore
    let rec dbatc (tcpl2_ : TcpListener) : unit =
        tcc.Reset () |> ignore
        printfn "Listening on port %d at %s" dspt sva
        tcpl2_.BeginAcceptTcpClient (new AsyncCallback (datcc), tcpl2_) |> ignore
        tcc.WaitOne () |> ignore
        dbatc tcpl2_
    let (laddr : IPAddress) = IPAddress.Parse sva
    let (tcpl : TcpListener) = new TcpListener (laddr, dspt)
    try
        tcpl.Start ()
        dbatc tcpl
        printfn "Exiting try block"
        printfn "Exiting runAsyncBE () normally"
    with
        | excp ->
            printfn "Error:  %s" excp.Message
            printfn "Exiting runAsyncBE () with error"

实施3 (我的实施基于the MSDN page for asynchronous workflows

let runAsyncA () : unit =
    printfn "Entering runAsyncA ()"
    let (laddr : IPAddress) = IPAddress.Parse sva
    let (svr : TcpListener) = new TcpListener (laddr, dspt)
    try
        svr.Start ()
        let (bta : byte array) = Array.zeroCreate<byte> imbs
        while true do
            printfn "Listening on port %d at %s" dspt sva
            let (cl : TcpClient) = svr.AcceptTcpClient ()
            let (ns : NetworkStream) = cl.GetStream ()
            async {respondToQuery ns bta} |> Async.RunSynchronously
            cl.Close ()
        svr.Stop ()
        printfn "Exiting runAsyncA () normally"
    with
        | excp ->
            printfn "Error:  %s" excp.Message
            printfn "Exiting runAsyncA () with error"

现在,从我阅读MSDN文档开始,我原本认为Implementation 3是最快的。但是当我从多台机器上查询多个查询时,它们都以大致相同的速度运行。这让我相信我一定做错了。

Implementation 2Implementation 3是&#34;是否正确&#34;实现在后台完成繁重工作的TcpListener的方法,并在完成时将响应返回给客户端,同时允许另一个客户端也可以在另一个后台线程中连接并启动另一个任务?如果没有,你能告诉我我应该读哪些课程(或教程)吗?

1 个答案:

答案 0 :(得分:6)

主循环的正确结构应如下所示:

let respondToQuery (client:TcpClient) = async {
  try
    let stream = client.GetStream()
    () // TODO: The actual processing goes here!
  finally
    client.Close() }

async {
  while true do 
    let! client = t.AcceptTcpClientAsync() |> Async.AwaitTask
    respondToQuery client |> Async.Start }

需要注意的关键事项是:

  • 我将主循环包装在async内,以便您可以使用AcceptTcpClientAsync异步等待客户端(不会阻塞)

  • respondToQuery函数返回使用Async.Start在后​​台启动的异步计算,以便处理可以在等待下一个客户端的同时继续(使用{{1}时你会阻止并等到Async.RunSynchronously完成)

  • 要使其完全异步,respondToQuery中的代码也需要使用流的异步操作 - 查找respondToQueryAsyncRead

您也可以使用AsyncWrite,在这种情况下,子计算(Async.StartChild的主体)获得与父项相同的取消令牌,因此当您取消主异步工作流时,它将取消所有孩子们:

respondToQuery

while true do let! client = t.AcceptTcpClientAsync() |> Async.AwaitTask do! respondToQuery client |> Async.StartChild |> Async.Ignore } 方法返回异步计算(使用Async.StartChildlet!启动),我们需要忽略它返回的令牌(可以用来等到孩子完成)。