F# UDP 发送字节引发 System.ArgumentOutOfRangeException 错误

F# UDP sending bytes raises System.ArgumentOutOfRangeException error

所以我有下面的 F# 代码,它应该创建一个 UDP 客户端,它应该能够发送和接收信息。但是,当我 运行 它时,出现以下错误:

Unhandled exception. System.ArgumentOutOfRangeException: Specified argument was out of the range of valid values. (Parameter 'bytes')
   at System.Net.Sockets.UdpClient.BeginSend(Byte[] datagram, Int32 bytes, IPEndPoint endPoint, AsyncCallback requestCallback, Object state)
   at System.Net.Sockets.UdpClient.<>c.<SendAsync>b__54_0(Byte[] targetDatagram, Int32 targetBytes, AsyncCallback callback, Object state)
   at System.Threading.Tasks.TaskFactory`1.FromAsyncImpl[TArg1,TArg2](Func`5 beginMethod, Func`2 endFunction, Action`1 endAction, TArg1 arg1, TArg2 arg2, Object state, TaskCreation
Options creationOptions)
   at System.Threading.Tasks.TaskFactory`1.FromAsync[TArg1,TArg2](Func`5 beginMethod, Func`2 endMethod, TArg1 arg1, TArg2 arg2, Object state)
   at System.Net.Sockets.UdpClient.SendAsync(Byte[] datagram, Int32 bytes)

错误指向我的函数send。错误可能来自哪里?我必须自己编码整个数据报吗:

Picture of UDP datagram/segment layout

下面是代码摘录:

let localIP = System.Net.IPAddress((int64) 0x0100007f) // Big endian
let portListen = 11000

let udpListener = new System.Net.Sockets.UdpClient(portListen, System.Net.Sockets.AddressFamily.InterNetwork)
let connect (ip: System.Net.IPAddress) (port:int) = udpListener.Connect(ip, port)

let send (msg : Byte[]) (port) = udpListener.SendAsync(msg, port).Start()
let receive () =
    let r = udpListener.ReceiveAsync()
    in (r.Start();r.Wait();r.Result.Buffer)


connect localIP portListen
let msg = System.Text.Encoding.ASCII.GetBytes("A")
send msg portListen
let result = receive ()
Console.WriteLine(result.ToString())

问题在这里:

udpListener.SendAsync(msg, port)

第二个参数不是端口,应该是你要发送的字节数。

所以正确的代码是:

udpListener.SendAsync(msg, msg.Length)