简体   繁体   English

Java 的 UDP _DatagramSocket.connect()_ 有什么作用?

[英]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.我最近看到了一个关于 Java UDP API 的小教程,我查看了DatagramSocketDatagramPacket类的 javadoc。 The class DatagramSocket contains several connect() and one disconnect() methods. DatagramSocket类包含几个connect()和一个disconnect()方法。 But isn't UDP a protocol without connections?但是UDP不是没有连接的协议吗?

What do these connect and disconnect methods do?这些connectdisconnect方法有什么作用?

From the javadocs of DatagramSocket#connect(InetAddress address, int port) :来自DatagramSocket#connect(InetAddress address, int port)的 javadocs :

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.当套接字连接时, receivesend不会对传入和传出的数据包执行任何安全检查,除了匹配数据包和套接字的地址和端口。 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.在发送操作中,如果设置了数据包的地址并且数据包的地址和套接字的地址不匹配,则会抛出IllegalArgumentException 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.因此,它实际上并不是一种像 TCP 那样建立“连接”的方法,而是一种防止向/从其他地址发送或接收数据包的方法。

One actual use case is managing concurrent calls of method receive() .一个实际用例是管理方法receive()并发调用。

Eg 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.例如,您有 2 个独立的通信流与 2 个网络节点,在 2 个独立的控制流 / Thread -s 中处理,每个Thread -s 在receive传入消息时都被阻塞。

Now, with disconnected DatagramSocket -s it is not defined, what Thread would catch what message.现在,使用断开连接的DatagramSocket -s 未定义,什么Thread将捕获什么消息。

But if you connect each of the sockets to the address of their corresponding node, incoming messages are delegated to the right control flow.但是,如果您将每个套接字连接到其对应节点的地址,传入的消息将被委托给正确的控制流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM