I've recently seen the a little tutorial about Java's UDP API and I've looked at the javadocs of the DatagramSocket
and DatagramPacket
classes. The class DatagramSocket
contains several connect()
and one disconnect()
methods. But isn't UDP a protocol without connections?
What do these connect
and disconnect
methods do?
From the javadocs of DatagramSocket#connect(InetAddress address, int port):
Connects the socket to a remote address for this socket. When a socket is connected to a remote address, packets may only be sent to or received from that address. By default a datagram socket is not connected.
...
When a socket is connected,
receive
andsend
will not perform any security checks on incoming and outgoing packets, other than matching the packet's and the socket's address and port. On a send operation, if the packet's address is set and the packet's address and the socket's address do not match, anIllegalArgumentException
will be thrown. A socket connected to a multicast address may only be used to send packets.
So it's not really a way to establish a "connection" the same way TCP does, but a way to prevent sending or receiving packets to/from other addresses.
One actual use case is managing concurrent calls of method receive()
.
E.g. you have 2 separate communication flows with 2 network nodes, handled in 2
separated control flows / Thread
-s, each of the Thread
-s blocked on receive
for incoming messages.
Now, with disconnected DatagramSocket
-s it is not defined, what Thread
would catch what message.
But if you connect each of the sockets to the address of their corresponding node, incoming messages are delegated to the right control flow.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With