The current library provides limited support for UDP packets. The UDP protocol is a connection-less and unreliable datagram based protocol. That means that messages sent may or may not arrive at the client side and may arrive in a different order as they are sent. UDP messages are often used for streaming media or for service discovery using the broadcasting mechanism.
- Similar to tcp_socket/1,
but create a socket using the
SOCK_DGRAMprotocol, ready for UDP connections.
- udp_receive(+Socket, -Data, -From, +Options)
- Wait for and return the next datagram. The data is returned as a Prolog
string object (see string_to_list/2). From
is a term of the format ip(A,B,C,D):Port
indicating the sender of the message. Socket can be waited
for using wait_for_input/3.
- Defines the returned term-type. Type is one of
- Specify the maximum number of bytes to read from a UDP datagram. Size must be within the range 0-65535. If unspecified, a maximum of 4096 bytes will be read.
The typical sequence to receive UDP data is:
receive(Port) :- udp_socket(S), tcp_bind(S, Port), repeat, udp_receive(Socket, Data, From, [as(atom)]), format('Got ~q from ~q~n', [Data, From]), fail.
- udp_send(+Socket, +Data, +To, +Options)
- Send a UDP message. Data is a string, atom or code-list providing the
data. To is an address of the form Host:Port
where Host is either the hostname or a term ip/4. Options
is currently unused.
A simple example to send UDP data is:
send(Host, Port, Message) :- udp_socket(S), udp_send(S, Message, Host:Port, ), tcp_close_socket(S).
A broadcast is achieved by using
tcp_setopt(Socket, broadcast)prior to sending the datagram and using the local network broadcast address as a ip/4 term.
The normal mechanism to discover a service on the local network is for the client to send a broadcast message to an agreed port. The server receives this message and replies to the client with a message indicating further details to establish the communication.