Java Reference
In-Depth Information
public DatagramSocket(int port, InetAddress interface) throws SocketException
This constructor is primarily used on multihomed hosts; it creates a socket that listens
for incoming datagrams on a specific port and network interface. The
port
argument
is the port on which this socket listens for datagrams. As with TCP sockets, you need
to be root on a Unix system to create a
DatagramSocket
on a port below 1024. The
address
argument is an
InetAddress
object matching one of the host's network ad‐
dresses. A
SocketException
is thrown if the socket can't be created. There are three
common reasons for this constructor to fail: the specified port is already occupied, you
are trying to connect to a port below 1024 and you're not root on a Unix system, or
address
is not the address of one of the system's network interfaces.
public DatagramSocket(SocketAddress interface) throws SocketException
This constructor is similar to the previous one except that the network interface address
and port are read from a
SocketAddress
. For example, this code fragment creates a
socket that only listens on the local loopback address:
SocketAddress
address
=
new
InetSocketAddress
(
"127.0.0.1"
,
9999
);
DatagramSocket
socket
=
new
DatagramSocket
(
address
);
protected DatagramSocket(DatagramSocketImpl impl) throws SocketException
This constructor enables subclasses to provide their own implementation of the UDP
protocol, rather than blindly accepting the default. Unlike sockets created by the other
four constructors, this socket is not initially bound to a port. Before using it, you have
to bind it to a
SocketAddress
using the
bind()
method:
public
void
bind
(
SocketAddress
addr
)
throws
SocketException
You can pass null to this method, binding the socket to any available address and port.
Sending and Receiving Datagrams
The primary task of the
DatagramSocket
class is to send and receive UDP datagrams.
One socket can both send and receive. Indeed, it can send and receive to and from
multiple hosts at the same time.
public void send(DatagramPacket dp) throws IOException
Once a
DatagramPacket
is created and a
DatagramSocket
is constructed, send the packet
by passing it to the socket's
send()
method. For example, if
theSocket
is a
Datagram
Socket
object and
theOutput
is a
DatagramPacket
object, send
theOutput
using
the
Socket
like this:
theSocket
.
send
(
theOutput
);
If there's a problem sending the data, this method may throw an
IOException
. However,
this is less common with
DatagramSocket
than
Socket
or
ServerSocket
, because the
unreliable nature of UDP means you won't get an exception just because the packet