The DatagramSocket Class
To send
or receive a DatagramPacket
, you need to open a
datagram socket. In Java, a datagram socket is created and accessed
through the DatagramSocket
class:
public class DatagramSocket extends Object
All datagram sockets are bound to a local port, on which they listen
for incoming data and which they place in the header of outgoing
datagrams. If you’re writing a client, you don’t care
what the local port is, so you call a constructor that lets the
system assign an unused port (an anonymous port). This port number is
placed in any outgoing datagrams and will be used by the server to
address any response datagrams. If you’re writing a server,
clients need to know on which port the server is listening for
incoming datagrams; therefore, when a server constructs a
DatagramSocket
, it must specify the local port on
which it will listen. However, the sockets used by clients and
servers are otherwise identical: they differ only in whether they use
an anonymous (system-assigned) or a well-known port. There’s no
distinction between client sockets and server sockets, as there is
with TCP; there is no such thing as a
DatagramServerSocket
.
The Constructors
The DatagramSocket
class has three constructors that are used in different situations,
much like the DatagramPacket
class. The first constructor opens a datagram socket on an anonymous local port. The second constructor opens a datagram socket on a well-known local port that listens to all local network interfaces. ...
Get Java Network Programming, Second Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.