6.6 UDP protocol support
The socket library provides support for UDP sockets. 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, may arrive in a different order then they were sent or even may arrive multiple times. UDP messages are often used for data replication, streaming media, or service discovery.
The library library(udp_broadcast)
provides a high-level
interface that builds on top of the library(broadcast)
facilitating an unreliable
publish-subscribe pattern based communication channel. The
library(udp_broadcast)
library supports multiple network
architectures, e.g., classical LAN broadcasting, multicast and
unicast.
- udp_socket(-Socket)
- Similar to tcp_socket/1,
but create a socket using the
SOCK_DGRAM
protocol, 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.
Defined Options:
- as(+Type)
- Defines the returned term-type. Type is one of
atom
,codes
orstring
(default). - max_message_size(+Size)
- 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.