I am writing a server in Ada that should listen and reply to messages received over UDP. I am using the GNAT.Sockets library and have created a socket and bound it to a port. However, I am not sure how to listen for and receive messages on the socket. The Listen_Socket function is for TCP sockets and it seems that using Stream with UDP sockets is not recommended. I have seen the receive_socket and receive_vector procedures as alternatives, but I am not sure how to use them or how to convert the output to a usable format.
I am writing a server that should reply to messages that it gets over UDP. A minimal example of what I have so far would look like this:
with GNAT.Sockets;use GNAT.Sockets; procedure udp is sock: Socket_Type; family: Family_Type:=Family_Inet; port: Port_Type:=12345; addr: Sock_Addr_Type(family); begin Create_Socket(sock,family,Socket_Datagram); addr.Addr:=Any_Inet_Addr; addr.Port:=port; Bind_Socket(sock,addr); -- Listen_Socket(sock); -- A TCP thing, not for UDP. -- now what? end UDP;
For a TCP socket, I can
accept, then use the
Stream function to get a nice way to read the data (as in
'Input). While the Stream function still exists, I have found an archive of a ten year old comp.lang.ada thread in which multiple people say not to use streams with UDP.
Looking in g-socket.ads, I do see alternatives: the
receive_vector procedures. However, the output of the former is a
Stream_Element_Array (with an
offset indicating the length), and the latter has something similar, just with some kind of length associated with each
According to https://stackoverflow.com/a/40045312/7105391, the way to change these types into a stream, is to not get them in the first place, and instead get a stream, which is not particularly helpful here.
Over at this github gist I found ,
Unchecked_Conversion is being used to turn the arrays into strings and vice versa, but given that the reference manual (13.13.1) says that
type Stream_Element is mod <implementation-defined>;, I'm not entirely comfortable using that approach.
All in all, I'm pretty confused about how I'm supposed to do this. I'm even more confused about the lack of examples online, as this should be a pretty basic thing to do.