编程语言
首页 > 编程语言> > Java的UDP _DatagramSocket.connect()_做什么?

Java的UDP _DatagramSocket.connect()_做什么?

作者:互联网

我最近看了一些有关Java UDP API的教程,并且看过DatagramSocket和DatagramPacket类的javadocs. DatagramSocket类包含几个connect()和一个connect()方法.但是UDP不是没有连接的协议吗?

这些连接和断开连接方法有什么作用?

解决方法:

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. 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.

因此,这实际上不是建立与TCP相同的“连接”的方法,而是一种防止与其他地址之间收发数据包的方法.

标签:connection,sockets,protocols,udp,java
来源: https://codeday.me/bug/20191028/1955386.html