gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 15:55:38 25 4
gpt4 key购买 nike

我正在尝试通过 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 }

现在,有不同的方式可以“同时”发送和接收,具体取决于“同时”的确切含义。可以在后台开始接收,然后同时发送,然后等待发送和接收都完成再循环:

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

关于asynchronous - 如何使用 F# 通过 UDP 异步接收和发送?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51812925/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com