Week 89 — What is the purpose of the `DatagramSocket` class and how can it be used?
Question of the Week #89
What is the purpose of the
DatagramSocket
class and how can it be used?3 Replies
While
Socket
allows communicating via TCP, DatagramSocket
can be used for sending and receiving UDP packets.
It is possible to receive UDP packets by first creating a DatagramPacket
object with a reference to a byte[]
and the number of bytes it is allowed to load into that array and then calling DatagramSocket#receive(DatagramPacket)
on the socket.
Similarly, UDP packets can be sent by creating a DatagramPacket
with the data to send and calling DatagramSocket#send(DatagramPacket)
with it.
For example, it is possible to create a server that is listening for UDP packets and always sending them back:
It is then also possible to write a client that sends some sample data to the server and receives the response:
📖 Sample answer from dan1st
Java DatagramSocket and DatagramPacket classes are used for connection-less socket programming using the UDP instead of TCP.
Submission from mitsuki087248