Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does Java's UDP _DatagramSocket.connect()_ do?

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?

like image 988
MinecraftShamrock Avatar asked Mar 17 '23 12:03

MinecraftShamrock


2 Answers

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 and send 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, an IllegalArgumentException 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.

like image 186
M A Avatar answered Mar 20 '23 02:03

M A


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.

like image 23
Sam Ginrich Avatar answered Mar 20 '23 03:03

Sam Ginrich