2

so I have the following F# code below which should create a UDP client and it should be able to send and receive information. However, when I run it, I get the following error:

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)

The error points to my function send. Where could the error come from? Do I have to encode the whole datagram myself:

Picture of UDP datagram/segment layout

Below is the code excerpt:

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())
Edelweiss
  • 79
  • 6

1 Answers1

2

Problem is here:

udpListener.SendAsync(msg, port)

The second parameter is not for port, is should be the number of bytes you want to send.

So the correct code would be:

udpListener.SendAsync(msg, msg.Length)
Nghia Bui
  • 3,694
  • 14
  • 21
  • Thanks, this fixed the issue, it was a logical error on my side and as you said correctly, the second argument is the length of the message. Thanks again! – Edelweiss Aug 01 '20 at 11:56