Specialized socket using the UDP protocol.
1 // ----- The client ----- 2 3 // Create a socket and bind it to the port 55001 4 auto socket = UdpSocket(); 5 socket.bind(55001); 6 7 // Send a message to 192.168.1.50 on port 55002 8 string message = "Hi, I am " ~ IpAddress.getLocalAddress().toString(); 9 socket.send(message, "192.168.1.50", 55002); 10 11 // Receive an answer (most likely from 192.168.1.50, but could be anyone else) 12 char[1024] buffer; 13 size_t received = 0; 14 IpAddress sender; 15 ushort port; 16 socket.receive(buffer, received, sender, port); 17 writeln( sender.toString(), " said: ", buffer[0 .. received]); 18 19 // ----- The server ----- 20 21 // Create a socket and bind it to the port 55002 22 auto socket = new UdpSocket(); 23 socket.bind(55002); 24 25 // Receive a message from anyone 26 char[1024] buffer; 27 size_t received = 0; 28 IpAddress sender; 29 ushort port; 30 socket.receive(buffer, received, sender, port); 31 writeln(sender.toString(), " said: ", buffer[0 .. received]); 32 33 // Send an answer 34 message = "Welcome " ~ sender.toString(); 35 socket.send(message, sender, port);
$(SOCKET_LINK), $(TCPSOCKET_LINK), $(PACKET_LINK)
A UDP socket is a connectionless socket.
Instead of connecting once to a remote host, like TCP sockets, it can send to and receive from any host at any time.
It is a datagram protocol: bounded blocks of data (datagrams) are transfered over the network rather than a continuous stream of data (TCP). Therefore, one call to send will always match one call to receive (if the datagram is not lost), with the same data that was sent.
The UDP protocol is lightweight but unreliable. Unreliable means that datagrams may be duplicated, be lost or arrive reordered. However, if a datagram arrives, its data is guaranteed to be valid.
UDP is generally used for real-time communication (audio or video streaming, real-time games, etc.) where speed is crucial and lost data doesn't matter much.
Sending and receiving data can use either the low-level or the high-level functions. The low-level functions process a raw sequence of bytes, whereas the high-level interface uses packets (see Packet), which are easier to use and provide more safety regarding the data that is exchanged. You can look at the Packet class to get more details about how they work.
It is important to note that UdpSocket is unable to send datagrams bigger than MaxDatagramSize. In this case, it returns an error and doesn't send anything. This applies to both raw data and packets. Indeed, even packets are unable to split and recompose data, due to the unreliability of the protocol (dropped, mixed or duplicated datagrams may lead to a big mess when trying to recompose a packet).
If the socket is bound to a port, it is automatically unbound from it when the socket is destroyed. However, you can unbind the socket explicitely with the Unbind function if necessary, to stop receiving messages or make the port available for other sockets.