java udp 指定端口接收数据.

2025-04-27 13:05:01
推荐回答(1个)
回答1:

请参考 API 文档中的说明

public class DatagramSocket

extends Object

This class represents a socket for sending and receiving datagram packets.
A datagram socket is the sending or receiving point for a packet
delivery service. Each packet sent or received on a datagram socket
is individually addressed and routed. Multiple packets sent from
one machine to another may be routed differently, and may arrive in
any order.
UDP broadcasts sends are always enabled on a DatagramSocket.
In order to receive broadcast packets a DatagramSocket
should be bound to the wildcard address. In some
implementations, broadcast packets may also be received when
a DatagramSocket is bound to a more specific address.
Example:

DatagramSocket s = new DatagramSocket(null);
s.bind(new InetSocketAddress(8888));

Which is equivalent to:

DatagramSocket s = new DatagramSocket(8888);

Both cases will create a DatagramSocket able to receive broadcasts on
UDP port 8888.

Since:
JDK1.0
See Also:
DatagramPacket,
DatagramChannel