如何使用 F# 通过 UDP 异步接收和发送?

How can I receive and send over UDP asynchronously with F#?

我正在尝试通过 UDP 制作消息传递应用程序,并使其能够同时连续发送和接收。我不知道如何实现这一目标并尝试了一些事情。下面是我到目前为止的代码,有人可以指出我做错了什么或我需要添加什么吗?谢谢。

open System
open System.Net
open System.Net.Sockets
open System.Text

printfn "Receive port: "
let receivePort = Console.ReadLine() |> int

let receivingClient = new UdpClient(receivePort)

let ReceivingIpEndPoint = new IPEndPoint(IPAddress.Any, 0)

printfn "Send address: "
let sendAddress = IPAddress.Parse(Console.ReadLine())

printfn "Send port: "
let sendPort = Console.ReadLine() |> int

let sendingClient = new UdpClient()

let sendingIpEndPoint = new IPEndPoint(sendAddress, sendPort)

let rec loop() =
    let receive = async {
        try
            let! receiveResult = receivingClient.ReceiveAsync() |> Async.AwaitTask
            let receiveBytes = receiveResult.Buffer
            let returnData = Encoding.ASCII.GetString(receiveBytes)
            printfn "%s" returnData
        with
            | error -> printfn "%s" error.Message
    }

    receive |> ignore

    printfn "Send message: "
    let (sendBytes: byte array) = Encoding.ASCII.GetBytes(Console.ReadLine())

    try
        sendingClient.Send(sendBytes, sendBytes.Length, sendingIpEndPoint) |> ignore
    with
        | error -> printfn "%s" error.Message

    loop()

loop()

Console.Read() |> ignore

您的代码的一个明显问题是您创建了一个异步计算 receive 然后忽略它,而没有启动它。这意味着您当前的版本只是发送。

我假设您打算在后台启动接收进程。为此,我们首先将 receivesend 定义为两个独立的异步函数:

let receive () = async {
    try
        let! receiveResult = receivingClient.ReceiveAsync() |> Async.AwaitTask
        let receiveBytes = receiveResult.Buffer
        let returnData = Encoding.ASCII.GetString(receiveBytes)
        printfn "%s" returnData
    with
        | error -> printfn "%s" error.Message }

let send () = async {
    printfn "Send message: "
    let (sendBytes: byte array) = Encoding.ASCII.GetBytes(Console.ReadLine())
    try
        sendingClient.Send(sendBytes, sendBytes.Length, sendingIpEndPoint) |> ignore
    with
        | error -> printfn "%s" error.Message }

现在,有多种发送和接收 "at the same time" 的方法,具体取决于 "at the same time" 的确切含义。可以在后台开始接收,然后同时发送,然后等待发送和接收都完成再循环:

let rec loop() = async {
    let! wait = Async.StartChild (receive ())
    do! send () 
    do! wait
    return! loop() }

loop() |> Async.Start

或者,您也可以启动两个循环,一个继续发送,另一个继续尽可能快地接收:

let rec loop1() = async {
    do! receive ()
    return! loop1() }

let rec loop2() = async {
    do! send ()
    return! loop2() }

loop1() |> Async.Start
loop2() |> Async.Start