Preface - Java Network Programming, 4th Edition (2013)

Java Network Programming, 4th Edition (2013)

Preface

Java’s growth over the past 20 years has been nothing short of phenomenal. Given Java’s rapid rise to prominence and the even more spectacular growth of the Internet, it’s a little surprising that network programming in Java remains so mysterious to so many. It doesn’t have to be. In fact, writing network programs in Java is quite simple, as this book will show. Readers with previous experience in network programming in a Unix, Windows, or Macintosh environment will be pleasantly surprised at how much easier it is to write equivalent programs in Java. The Java core API includes well-designed interfaces to most network features. Indeed, there is very little application layer network software you can write in C or C++ that you can’t write more easily in Java. Java Network Programming, Fourth Edition, endeavors to show you how to take advantage of Java’s network class library to quickly and easily write programs that accomplish many common networking tasks. Some of these include:

§ Browsing the Web with HTTP

§ Writing multithreaded servers

§ Encrypting communications for confidentiality, authentication, and guaranteed message integrity

§ Designing GUI clients for network services

§ Posting data to server-side programs

§ Looking up hosts using DNS

§ Downloading files with anonymous FTP

§ Connecting sockets for low-level network communication

§ Multicasting to all hosts on the network

Java is the first (though no longer the only) language to provide such a powerful cross-platform network library for handling all these diverse tasks. Java Network Programming exposes the power and sophistication of this library. This book’s goal is to enable you to start using Java as a platform for serious network programming. To do so, this book provides a general background in network fundamentals, as well as detailed discussions of Java’s facilities for writing network programs. You’ll learn how to write Java programs that share data across the Internet for games, collaboration, software updates, file transfer, and more. You’ll also get a behind-the-scenes look at HTTP, SMTP, TCP/IP, and the other protocols that support the Internet and the Web. When you finish this book, you’ll have the knowledge and the tools to create the next generation of software that takes full advantage of the Internet.

About the Fourth Edition

In 1996, in the first edition of this book’s opening chapter, I wrote extensively about the sort of dynamic, distributed network applications I thought Java would make possible. One of the most exciting parts of writing subsequent editions has been seeing virtually all of the applications I foretold come to pass. Programmers are using Java to query database servers, monitor web pages, control telescopes, manage multiplayer games, and more, all by using Java’s native ability to access the Internet. Java in general and network programming in Java in particular has moved well beyond the hype stage and into the realm of real, working applications.

This book has come a long way, too. The fourth edition focuses even more heavily on HTTP and REST. HTTP has gone from being one of many network protocols to almost the network protocol. As you’ll see, it is often the protocol on which other protocols are built, forming its own layer in the network stack.

There have been lots of other small changes and updates throughout the java.net and supporting packages in Java 6, 7, and 8, and these are covered here as well. New classes addressed in this edition include CookieManager, CookiePolicy, CookieStore, HttpCookie,SwingWorker, Executor, ExecutorService, AsynchronousSocketChannel, AsynchronousServerSocketChannel, and more. Many other methods have been added to existing classes in the last three releases of Java, and these are discussed in the relevant chapters. I’ve also rewritten large parts of the book to reflect the ever-changing fashions in Java programming in general and network programming in particular. I hope you’ll find this fourth edition an even stronger, longer-lived, more accurate, and more enjoyable tutorial and reference to network programming in Java than the previous one.

Organization of the Book

Chapter 1, Basic Network Concepts, explains in detail what a programmer needs to know about how the networks and the Internet work. It covers the protocols that underlie the Internet, such as TCP/IP and UDP/IP.

The next two chapters throw some light on two parts of Java programming that are critical to almost all network programs but are often misunderstood and misused: I/O and threading. Chapter 2, Streams, explores Java’s classic I/O which—despite the new I/O APIs—isn’t going away any time soon and is still the preferred means of handling input and output in most client applications. Understanding how Java handles I/O in the general case is a prerequisite for understanding the special case of how Java handles network I/O. Chapter 3, Threads, explores multithreading and synchronization, with a special emphasis on how they can be used for asynchronous I/O and network servers.

Experienced Java programmers may be able to skim or skip these two chapters. However, Chapter 4, Internet Addresses, is essential reading for everyone. It shows how Java programs interact with the Domain Name System through the InetAddress class, the one class that’s needed by essentially all network programs. Once you’ve finished this chapter, it’s possible to jump around in the book as your interests and needs dictate.

Chapter 5, URLs and URIs, explores Java’s URL class, a powerful abstraction for downloading information and files from network servers of many kinds. The URL class enables you to connect to and download files and documents from a network server without concerning yourself with the details of the protocol the server speaks. It lets you connect to an FTP server using the same code you use to talk to an HTTP server or to read a file on the local hard disk. You’ll also learn about the newer URI class, a more standards-conformant alternative for identifying but not retrieving resources.

Chapter 6, HTTP, delves deeper into the HTTP protocol specifically. Topics covered include REST, HTTP headers, and cookies. Chapter 7, URLConnections, shows you how to use the URLConnection and HttpURLConnection classes not just to download data from web servers, but to upload documents and configure connections.

Chapter 8 through Chapter 10 discuss Java’s low-level socket classes for network access. Chapter 8, Sockets for Clients, introduces the Java sockets API and the Socket class in particular. It shows you how to write network clients that interact with TCP servers of all kinds including whois, dict, and HTTP. Chapter 9, Sockets for Servers, shows you how to use the ServerSocket class to write servers for these and other protocols. Finally, Chapter 10, Secure Sockets, shows you how to protect your client-server communications using the Secure Sockets Layer (SSL) and the Java Secure Sockets Extension (JSSE).

Chapter 11, Nonblocking I/O, introduces the new I/O APIs specifically designed for network servers. These APIs enable a program to figure out whether a connection is ready before it tries to read from or write to the socket. This allows a single thread to manage many different connections simultaneously, thereby placing much less load on the virtual machine. The new I/O APIs don’t help much for small servers or clients that don’t open many simultaneous connections, but they may provide performance boosts for high-volume servers that want to transmit as much data as the network can handle as fast as the network can deliver it.

Chapter 12, UDP, introduces the User Datagram Protocol (UDP) and the associated DatagramPacket and DatagramSocket classes that provide fast, unreliable communication. Finally, Chapter 13, IP Multicast, shows you how to use UDP to communicate with multiple hosts at the same time.

Who You Are

This book assumes you are comfortable with the Java language and programming environment, in addition to object-oriented programming in general. This book does not attempt to be a basic language tutorial. You should be thoroughly familiar with the syntax of Java. You should have written simple applications. It also wouldn’t hurt if you’re familiar with basic Swing programming, though that’s not required aside from a few examples. When you encounter a topic that requires a deeper understanding for network programming than is customary—for instance, threads and streams—I’ll cover that topic as well, at least briefly.

However, this book doesn’t assume that you have prior experience with network programming. You should find it a complete introduction to networking concepts and network application development. I don’t assume that you have a few thousand networking acronyms (TCP, UDP, SMTP, etc.) at the tip of your tongue. You’ll learn what you need to know about these here.

Java Versions

Java’s network classes have changed a lot more slowly since Java 1.0 than other parts of the core API. In comparison to the AWT or I/O, there have been almost no changes and only a few additions. Of course, all network programs make extensive use of the I/O classes and some make heavy use of GUIs. This book is written with the assumption that you are coding with at least Java 5.0. In general, I use Java 5 features like generics and the enhanced for loop freely without further explanation.

For network programming purposes, the distinction between Java 5 and Java 6 is not large. Most examples look identical in the two versions. When a particular method or class is new in Java 6, 7, or 8, it is noted by a comment following its declaration like this:

public void setFixedLengthStreamingMode(long contentLength) // Java 7

Java 7 is a bit more of a stretch. I have not shied away from using features introduced in Java 7 where they seemed especially useful or convenient—for instance, try-with-resources and multicatch are both very helpful when trying to fit examples into the limited space available in a printed book—but I have been careful to point out my use of such features.

Overall, though, Java’s networking API has been relatively stable since Java 1.0. Very little of the post-1.0 networking API has ever been deprecated, and additions have been relatively minor. You shouldn’t have any trouble using this book after Java 8 is released. New APIs, however, have been somewhat more frequent in the supporting classes, particularly I/O, which has undergone three major revisions since Java 1.0.

About the Examples

Most methods and classes described in this book are illustrated with at least one complete working program, simple though it may be. In my experience, a complete working program is essential to showing the proper use of a method. Without a program, it is too easy to drop into jargon or to gloss over points about which the author may be unclear in his own mind. The Java API documentation itself often suffers from excessively terse descriptions of the method calls. In this book, I have tried to err on the side of providing too much explication rather than too little. If a point is obvious to you, feel free to skip over it. You do not need to type in and run every example in this book; but if a particular method does give you trouble, you should have at least one working example.

Each chapter includes at least one (and often several) more complex programs that demonstrate the classes and methods of that chapter in a more realistic setting. These often rely on Java features not discussed in this book. Indeed, in many of the programs, the networking components are only a small fraction of the source code and often the least difficult parts. Nonetheless, none of these programs could be written as easily in languages that didn’t give networking the central position it occupies in Java. The apparent simplicity of the networked sections of the code reflects the extent to which networking has been made a core feature of Java, and not any triviality of the program itself. All example programs presented in this book are available online, often with corrections and additions. You can download the source code from http://www.cafeaulait.org/books/jnp4/.

I have tested all the examples on Linux and many on Windows and Mac OS X. Most of the examples given here should work on other platforms and with other compilers and virtual machines that support Java 5 or later. The most common reasons an example may not compile with Java 5 or 6 are try-with-resources and multicatch. These examples can easily be rewritten to support earlier Java versions at the cost of increased verbosity.

I do feel a little guilty about a couple of compromises necessitated by the needs of space in a printed book. First, I rarely check preconditions. Most methods assume they are passed good data, and dispense with null checks and similar principles of good code hygiene. Furthermore, I have reduced the indentation to two characters per block and four characters per continuation line, as opposed to the Java standard of four and eight, respectively. I hope these flaws will not be too distracting. On the positive side, these compromises have aided me in making this edition considerably shorter (by several hundred pages) than the previous edition.

Conventions Used in This Book

Body text is Minion Pro, normal, like you’re reading now.

A monospaced typewriter font is used for:

§ Code examples and fragments

§ Anything that might appear in a Java program, including keywords, operators, data types, method names, variable names, class names, and interface names

§ Program output

§ Tags that might appear in an HTML document

A bold monospaced font is used for:

§ Command lines and options that should be typed verbatim on the screen

An italicized font is used for:

§ New terms where they are defined

§ Pathnames, filenames, and program names (however, if the program name is also the name of a Java class, it is given in a monospaced font, like other class names)

§ Host and domain names (www.hpmor.com)

§ URLs (http://www.cafeaulait.org/slides/)

§ Titles of other books (Java I/O)

TIP

Indicates a tip, suggestion, or general note.

WARNING

Indicates a warning or caution.

Significant code fragments and complete programs are generally placed into a separate paragraph, like this:

Socket s = new Socket("java.oreilly.com", 80);

if (!s.getTcpNoDelay()) s.setTcpNoDelay(true);

When code is presented as fragments rather than complete programs, the existence of the appropriate import statements should be inferred. For example, in the preceding code fragment you may assume that java.net.Socket was imported.

Some examples intermix user input with program output. In these cases, the user input will be displayed in bold, as in this example from Chapter 9:

% telnet rama.poly.edu 7

Trying 128.238.10.212...

Connected to rama.poly.edu.

Escape character is '^]'.

This is a test

This is a test

This is another test

This is another test

9876543210

9876543210

^]

telnet> close

Connection closed.

Finally, although many of the examples used here are toy examples unlikely to be reused, a few of the classes I develop have real value. Please feel free to reuse them or any parts of them in your own code. No special permission is required. They are in the public domain (although the same is most definitely not true of the explanatory text!).