Skip to Content
Java Network Programming, Second Edition
book

Java Network Programming, Second Edition

by Elliotte Rusty Harold
August 2000
Intermediate to advanced
760 pages
21h
English
O'Reilly Media, Inc.
Content preview from Java Network Programming, Second Edition

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Java Network Programming, 4th Edition

Java Network Programming, 4th Edition

Elliotte Rusty Harold
Java Concurrency, 2/e

Java Concurrency, 2/e

Douglas Schmidt

Publisher Resources

ISBN: 1565928709Supplemental ContentCatalog PageErrata