Java Network Programming Fourth Edition Elliotte Rusty Harold install download https://ebookname.com/product/java-network-programming-fourth- edition-elliotte-rusty-harold/ Get the full ebook with Bonus Features for a Better Reading Experience on ebookname.com
Instant digital products (PDF, ePub, MOBI) available Download now and explore formats that suit you... XML in a nutshell 3rd ed Edition Elliotte Rusty Harold https://ebookname.com/product/xml-in-a-nutshell-3rd-ed-edition- elliotte-rusty-harold/ Linear programming and network flows Fourth Edition M. S. Bazaraa https://ebookname.com/product/linear-programming-and-network- flows-fourth-edition-m-s-bazaraa/ Java Programming 5th Edition Joyce Farrell https://ebookname.com/product/java-programming-5th-edition-joyce- farrell/ Scott 2007 Standard Postage Stamp Catalogue Vol 6 Countries of the World So Z 163rd Edition James E. Kloetzel https://ebookname.com/product/scott-2007-standard-postage-stamp- catalogue-vol-6-countries-of-the-world-so-z-163rd-edition-james- e-kloetzel/
601 great scrapbook ideas 1st ed Edition Memory Makers Books https://ebookname.com/product/601-great-scrapbook-ideas-1st-ed- edition-memory-makers-books/ On Percs Facebooking While Intoxicated 1st Edition Mike Rainey https://ebookname.com/product/on-percs-facebooking-while- intoxicated-1st-edition-mike-rainey/ If Not Now When Writings in Defense of Europe 1st Edition Mathijs Koenraadt https://ebookname.com/product/if-not-now-when-writings-in- defense-of-europe-1st-edition-mathijs-koenraadt/ Research for Development A Practical Guide 1st Edition Sophie Laws https://ebookname.com/product/research-for-development-a- practical-guide-1st-edition-sophie-laws/ A Slice of Organic Life 1st Edition Sheherazade Goldsmith https://ebookname.com/product/a-slice-of-organic-life-1st- edition-sheherazade-goldsmith/
Handbook of Diabetes 4th Edition Rudy Bilous https://ebookname.com/product/handbook-of-diabetes-4th-edition- rudy-bilous/
Elliotte Rusty Harold FOURTH EDITION Java Network Programming
Java Network Programming, Fourth Edition by Elliotte Rusty Harold Copyright © 2014 Elliotte Rusty Harold. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are alsoavailableformosttitles(http://my.safaribooksonline.com).Formoreinformation,contactourcorporate/ institutional sales department: 800-998-9938 or corporate@oreilly.com. Editor: Meghan Blanchette Production Editor: Nicole Shelby Copyeditor: Kim Cofer Proofreader: Jasmine Kwityn Indexer: Judy McConville Cover Designer: Randy Comer Interior Designer: David Futato Illustrator: Rebecca Demarest October 2013: Fourth Edition Revision History for the Fourth Edition: 2013-09-23: First release See http://oreilly.com/catalog/errata.csp?isbn=9781449357672 for release details. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Java Network Programming, the image of a North American river otter, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trade‐ mark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. ISBN: 978-1-449-35767-2 [LSI]
This book is dedicated to my dog, Thor.
Table of Contents Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii 1. Basic Network Concepts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Networks 2 The Layers of a Network 4 The Host-to-Network Layer 7 The Internet Layer 8 The Transport Layer 9 The Application Layer 10 IP, TCP, and UDP 10 IP Addresses and Domain Names 11 Ports 13 The Internet 14 Internet Address Blocks 15 Network Address Translation 15 Firewalls 15 Proxy Servers 16 The Client/Server Model 18 Internet Standards 19 IETF RFCs 20 W3C Recommendations 22 2. Streams. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 Output Streams 26 Input Streams 31 Marking and Resetting 34 Filter Streams 35 Chaining Filters Together 37 Buffered Streams 38 v
PrintStream 39 Data Streams 41 Readers and Writers 44 Writers 45 OutputStreamWriter 47 Readers 47 Filter Readers and Writers 49 PrintWriter 51 3. Threads. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 Running Threads 55 Subclassing Thread 56 Implementing the Runnable Interface 58 Returning Information from a Thread 60 Race Conditions 61 Polling 63 Callbacks 63 Futures, Callables, and Executors 68 Synchronization 70 Synchronized Blocks 72 Synchronized Methods 74 Alternatives to Synchronization 75 Deadlock 77 Thread Scheduling 78 Priorities 78 Preemption 79 Thread Pools and Executors 89 4. Internet Addresses. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 The InetAddress Class 95 Creating New InetAddress Objects 95 Getter Methods 100 Address Types 102 Testing Reachability 106 Object Methods 106 Inet4Address and Inet6Address 107 The NetworkInterface Class 108 Factory Methods 108 Getter Methods 110 Some Useful Programs 111 SpamCheck 111 vi | Table of Contents
Processing Web Server Logfiles 112 5. URLs and URIs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 URIs 117 URLs 120 Relative URLs 122 The URL Class 123 Creating New URLs 123 Retrieving Data from a URL 128 Splitting a URL into Pieces 135 Equality and Comparison 139 Conversion 141 The URI Class 141 Constructing a URI 142 The Parts of the URI 144 Resolving Relative URIs 147 Equality and Comparison 148 String Representations 149 x-www-form-urlencoded 149 URLEncoder 150 URLDecoder 154 Proxies 154 System Properties 155 The Proxy Class 155 The ProxySelector Class 156 Communicating with Server-Side Programs Through GET 157 Accessing Password-Protected Sites 161 The Authenticator Class 162 The PasswordAuthentication Class 164 The JPasswordField Class 164 6. HTTP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 The Protocol 169 Keep-Alive 175 HTTP Methods 177 The Request Body 179 Cookies 181 CookieManager 184 CookieStore 185 7. URLConnections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187 Opening URLConnections 188 Table of Contents | vii
Reading Data from a Server 189 Reading the Header 190 Retrieving Specific Header Fields 191 Retrieving Arbitrary Header Fields 197 Caches 199 Web Cache for Java 203 Configuring the Connection 208 protected URL url 209 protected boolean connected 209 protected boolean allowUserInteraction 210 protected boolean doInput 211 protected boolean doOutput 212 protected boolean ifModifiedSince 212 protected boolean useCaches 214 Timeouts 215 Configuring the Client Request HTTP Header 215 Writing Data to a Server 218 Security Considerations for URLConnections 223 Guessing MIME Media Types 224 HttpURLConnection 224 The Request Method 225 Disconnecting from the Server 229 Handling Server Responses 230 Proxies 235 Streaming Mode 235 8. Sockets for Clients. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237 Using Sockets 237 Investigating Protocols with Telnet 238 Reading from Servers with Sockets 240 Writing to Servers with Sockets 246 Constructing and Connecting Sockets 251 Basic Constructors 251 Picking a Local Interface to Connect From 253 Constructing Without Connecting 254 Socket Addresses 255 Proxy Servers 256 Getting Information About a Socket 257 Closed or Connected? 258 toString() 259 Setting Socket Options 259 TCP_NODELAY 260 viii | Table of Contents
SO_LINGER 261 SO_TIMEOUT 261 SO_RCVBUF and SO_SNDBUF 262 SO_KEEPALIVE 263 OOBINLINE 264 SO_REUSEADDR 265 IP_TOS Class of Service 265 Socket Exceptions 267 Sockets in GUI Applications 268 Whois 269 A Network Client Library 272 9. Sockets for Servers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283 Using ServerSockets 283 Serving Binary Data 288 Multithreaded Servers 289 Writing to Servers with Sockets 293 Closing Server Sockets 295 Logging 297 What to Log 297 How to Log 298 Constructing Server Sockets 302 Constructing Without Binding 304 Getting Information About a Server Socket 305 Socket Options 306 SO_TIMEOUT 307 SO_REUSEADDR 308 SO_RCVBUF 308 Class of Service 309 HTTP Servers 309 A Single-File Server 310 A Redirector 314 A Full-Fledged HTTP Server 319 10. Secure Sockets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325 Secure Communications 326 Creating Secure Client Sockets 328 Choosing the Cipher Suites 332 Event Handlers 336 Session Management 336 Client Mode 338 Creating Secure Server Sockets 339 Table of Contents | ix
Configuring SSLServerSockets 343 Choosing the Cipher Suites 343 Session Management 344 Client Mode 344 11. Nonblocking I/O. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347 An Example Client 349 An Example Server 353 Buffers 359 Creating Buffers 361 Filling and Draining 363 Bulk Methods 364 Data Conversion 365 View Buffers 368 Compacting Buffers 370 Duplicating Buffers 372 Slicing Buffers 376 Marking and Resetting 377 Object Methods 377 Channels 378 SocketChannel 378 ServerSocketChannel 381 The Channels Class 383 Asynchronous Channels (Java 7) 384 Socket Options (Java 7) 386 Readiness Selection 388 The Selector Class 388 The SelectionKey Class 390 12. UDP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393 The UDP Protocol 393 UDP Clients 395 UDP Servers 397 The DatagramPacket Class 399 The Constructors 401 The get Methods 403 The setter Methods 406 The DatagramSocket Class 408 The Constructors 409 Sending and Receiving Datagrams 411 Managing Connections 416 Socket Options 417 x | Table of Contents
SO_TIMEOUT 417 SO_RCVBUF 418 SO_SNDBUF 419 SO_REUSEADDR 419 SO_BROADCAST 419 IP_TOS 420 Some Useful Applications 421 Simple UDP Clients 421 UDPServer 425 A UDP Echo Client 428 DatagramChannel 431 Using DatagramChannel 431 13. IP Multicast. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443 Multicasting 444 Multicast Addresses and Groups 447 Clients and Servers 450 Routers and Routing 452 Working with Multicast Sockets 453 The Constructors 454 Communicating with a Multicast Group 455 Two Simple Examples 460 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465 Table of Contents | xi
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 com‐ mon 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 Program‐ ming exposes the power and sophistication of this library. This book’s goal is to enable xiii
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 dis‐ cussions 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, AsynchronousSocketChan nel, 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 pre‐ vious one. Organization of the Book Chapter1,Basic Network Concepts,explainsindetailwhataprogrammerneedstoknow about how the networks and the Internet work. It covers the protocols that underlie the Internet, such as TCP/IP and UDP/IP. xiv | Preface
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. ExperiencedJavaprogrammersmaybeabletoskimorskipthesetwochapters.However, Chapter 4, Internet Addresses, is essential reading for everyone. It shows how Java pro‐ grams 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 chap‐ ter, 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 down‐ loadinginformationandfilesfromnetworkserversofmanykinds.TheURLclassenables 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 communica‐ tions 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. Preface | xv
Chapter 12, UDP, introduces the User Datagram Protocol (UDP) and the associated DatagramPacket and DatagramSocket classes that provide fast, unreliable communi‐ cation. 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 en‐ vironment, 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 syntaxofJava.Youshouldhavewrittensimpleapplications.Italsowouldn’thurtifyou’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 net‐ work 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 pro‐ gramming. You should find it a complete introduction to networking concepts and network application development. I don’t assume that you have a few thousand net‐ working 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 xvi | Preface
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, par‐ ticularly 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 com‐ plete 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 exces‐ sively 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 ap‐ parent 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.cafeau lait.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. Preface | xvii
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) Indicates a tip, suggestion, or general note. 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); xviii | Preface
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!). Request for Comments I enjoy hearing from readers, whether with general comments about this book, specific corrections, other topics they would like to see covered, or just war stories about their own network programming travails. You can reach me by sending an email to elharo@ibiblio.org.Pleaserealize,however,thatIreceiveseveralhundredpiecesofemail a day and cannot personally respond to each one. For the best chance of getting a per‐ sonal response, please identify yourself as a reader of this book. If you have a question about a particular program that isn’t working as you expect, try to reduce it to the simplest case that reproduces the bug, preferably a single class, and paste the text of the entire program into the body of your email. Unsolicited attachments will be deleted unopened. And please, please send the message from the account you want me to reply to and make sure that your Reply-to address is properly set! There’s nothing quite so frustrating as spending an hour or more carefully researching the answer to an inter‐ esting question and composing a detailed response, only to have it bounce because my correspondentsentherfeedbackfromapublicterminalandneglectedtosetthebrowser preferences to include her actual email address. I also adhere to the old saying “If you like this book, tell your friends. If you don’t like it, tell me.” I’m especially interested in hearing about mistakes. This is the fourth edition. I’ve yet to make it perfect, but I keep trying. As hard as I and the editors at O’Reilly Preface | xix
workedonthisbook,I’msuretherearemistakesandtypographicalerrorsthatwemissed here somewhere. And I’m sure that at least one of them is a really embarrassing whopper of a problem. If you find a mistake or a typo, please let me know so I can correct it. I’ll post it on the O’Reilly website at http://oreil.ly/java_np_errata. Before reporting errors, please check one of those pages to see if I already know about it and have posted a fix. Any errors that are reported will be fixed in future printings. Using Code Examples This book is here to help you get your job done. In general, if this book includes code examples, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require per‐ mission. We appreciate, but do not require, attribution. An attribution usually includes the title, author,publisher,andISBN.Forexample:“JavaNetworkProgramming,FourthEdition, by Elliotte Rusty Harold (O’Reilly). Copyright 2014 Elliotte Rusty Harold, 978-1-449-35767-2.” If you feel your use of code examples falls outside fair use or the permission given here, feel free to contact us at permissions@oreilly.com. Safari® Books Online Safari Books Online is an on-demand digital library that delivers expert content in both book and video form from the world’s lead‐ ing authors in technology and business. Technology professionals, software developers, web designers, and business and crea‐ tive professionals use Safari Books Online as their primary resource for research, prob‐ lem solving, learning, and certification training. Safari Books Online offers a range of product mixes and pricing programs for organi‐ zations, government agencies, and individuals. Subscribers have access to thousands of books, training videos, and prepublication manuscripts in one fully searchable database from publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley Pro‐ fessional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technol‐ xx | Preface
ogy, and dozens more. For more information about Safari Books Online, please visit us online. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at http://oreil.ly/java-network-prgamming. To comment or ask technical questions about this book, send email to bookques tions@oreilly.com. For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com. Find us on Facebook: http://facebook.com/oreilly Follow us on Twitter: http://twitter.com/oreillymedia Watch us on YouTube: http://www.youtube.com/oreillymedia Acknowledgments Many people were involved in the production of this book. My editor, Mike Loukides, gotthingsrolling,andprovidedmanyhelpfulcommentsalongthewaythatsubstantially improved the book. Dr. Peter “Peppar” Parnes helped out immensely with Chapter 13. The technical editors all provided invaluable assistance in hunting down errors and omissions. Simon St. Laurent provided crucial advice on which topics deserved more coverage. Scott Oaks lent his thread expertise to Chapter 3, proving once again by the many subtle bugs he hunted down that multithreading still requires the attention of an expert. Ron Hitchens shone light into many of the darker areas of the new I/O APIs. Marc Loy and Jim Elliott reviewed some of the most bleeding edge material in the book. Timothy F. Rohaly was unswerving in his commitment to making sure I closed all my socketsandcaughtallpossibleexceptions,andingeneralwrotethecleanest,safest,most exemplary code I could write. John Zukowski found numerous errors of omission, all nowfilledthankstohim.Andtheeagle-eyedAvnerGelbdisplayedanastonishingability to spot mistakes that had somehow managed to go unnoticed by myself, all the other Preface | xxi
editors, and the tens of thousands of readers of the first edition. Alex Stangl and Ryan Cuprak provided further assistance with spotting both new and lingering mistakes in this latest edition. It isn’t customary to thank the publisher, but the publisher does set the tone for the rest of the company, authors, editors, and production staff alike; and I think Tim O’Reilly deserves special credit for making O’Reilly Media absolutely one of the best houses an author can write for. If there’s one person without whom this book would never have been written, it’s him. If you, the reader, find O’Reilly books to be consistently better than most of the dreck on the market, the reason really can be traced straight back to Tim. My agent, David Rogelberg, convinced me it was possible to make a living writing books like this rather than working in an office. The entire crew at ibiblio.org over the last several years has really helped me to communicate better with my readers in a variety of ways. Every reader who sent in bouquets and brickbats for previous editions has been instrumental in helping me write this much-improved edition. All these people deserve much thanks and credit. Finally, as always, I’d like to offer my largest thanks to my wife, Beth, without whose love and support this book would never have happened. —Elliotte Rusty Harold elharo@ibiblio.org July 5, 2013 xxii | Preface
CHAPTER 1 Basic Network Concepts Network programming is no longer the province of a few specialists. It has become a core part of every developer’s toolbox. Today, more programs are network aware than aren’t. Besides classic applications like email, web browsers, and remote login, most major applications have some level of networking built in. For example: • Text editors like BBEdit save and open files directly from FTP servers. • IDEs like Eclipse and IntelliJ IDEA communicate with source code repositories like GitHub and Sourceforge. • Word processors like Microsoft Word open files from URLs. • Antivirus programs like Norton AntiVirus check for new virus definitions by con‐ necting to the vendor’s website every time the computer is started. • Music players like Winamp and iTunes upload CD track lengths to CDDB and download the corresponding track titles. • Gamers playing multiplayer first-person shooters like Halo gleefully frag each other in real time. • Supermarket cash registers running IBM SurePOS ACE communicate with their store’s server in real time with each transaction. The server uploads its daily receipts to the chain’s central computers each night. • Schedule applications like Microsoft Outlook automatically synchronize calendars among employees in a company. Java was the first programming language designed from the ground up for network applications. Java was originally aimed at proprietary cable television networks rather than the Internet, but it’s always had the network foremost in mind. One of the first two real Java applications was a web browser. As the Internet continues to grow, Java is uniquely suited to build the next generation of network applications. 1
One of the biggest secrets about Java is that it makes writing network programs easy. In fact, it is far easier to write network programs in Java than in almost any other language. This book shows you dozens of complete programs that take advantage of the Internet. Some are simple textbook examples, while others are completely functional applica‐ tions. One thing you’ll notice in the fully functional applications is just how little code is devoted to networking. Even in network-intensive programs like web servers and clients, almost all the code handles data manipulation or the user interface. The part of the program that deals with the network is almost always the shortest and simplest. In brief, it is easy for Java applications to send and receive data across the Internet. This chapter covers the background networking concepts you need to understand be‐ fore writing networked programs in Java (or, for that matter, in any language). Moving from the most general to the most specific, it explains what you need to know about networks in general, IP and TCP/IP-based networks in particular, and the Internet. This chapter doesn’t try to teach you how to wire a network or configure a router, but you will learn what you need to know to write applications that communicate across the Internet.Topicscoveredinthischapterincludethenatureofnetworks;theTCP/IPlayer model; the IP, TCP, and UDP protocols; firewalls and proxy servers; the Internet; and the Internet standardization process. Experienced network gurus may safely skip this chapter, and move on to the next chapter where you begin developing the tools needed to write your own network programs in Java. Networks A network is a collection of computers and other devices that can send data to and receive data from one another, more or less in real time. A network is often connected by wires, and the bits of data are turned into electromagnetic waves that move through the wires. However, wireless networks transmit data using radio waves; and most long- distance transmissions are now carried over fiber-optic cables that send light waves through glass filaments. There’s nothing sacred about any particular physical medium for the transmission of data. Theoretically, data could be transmitted by coal-powered computers that send smoke signals to one another. The response time (and environ‐ mental impact) of such a network would be rather poor. Each machine on a network is called a node. Most nodes are computers, but printers, routers, bridges, gateways, dumb terminals, and Coca-Cola™ machines can also be no‐ des. You might use Java to interface with a Coke machine, but otherwise you’ll mostly talk to other computers. Nodes that are fully functional computers are also called hosts. I will use the word node to refer to any device on the network, and the word host to refer to a node that is a general-purpose computer. Every network node has an address, a sequence of bytes that uniquely identifies it. You can think of this group of bytes as a number, but in general the number of bytes in an address or the ordering of those bytes (big endian or little endian) is not guaranteed to 2 | Chapter 1: Basic Network Concepts
match any primitive numeric data type in Java. The more bytes there are in each address, the more addresses there are available and the more devices that can be connected to the network simultaneously. Addresses are assigned differently on different kinds of networks. Ethernet addresses are attached to the physical Ethernet hardware. Manufacturers of Ethernet hardware use preassigned manufacturer codes to make sure there are no conflicts between the addresses in their hardware and the addresses of other manufacturers’ hardware. Each manufacturer is responsible for making sure it doesn’t ship two Ethernet cards with the same address. Internet addresses are normally assigned to a computer by the organi‐ zation that is responsible for it. However, the addresses that an organization is allowed to choose for its computers are assigned by the organization’s Internet service provider (ISP). ISPs get their IP addresses from one of four regional Internet registries (the reg‐ istry for North America is ARIN, the American Registry for Internet Numbers), which are in turn assigned IP addresses by the Internet Corporation for Assigned Names and Numbers (ICANN). On some kinds of networks, nodes also have text names that help human beings identify them such as “www.elharo.com” or “Beth Harold’s Computer.” At a set moment in time, aparticularnamenormallyreferstoexactlyoneaddress.However,namesarenotlocked to addresses. Names can change while addresses stay the same; likewise, addresses can change while the names stay the same. One address can have several names and one name can refer to several different addresses. All modern computer networks are packet-switched networks: data traveling on the network is broken into chunks called packets and each packet is handled separately. Each packet contains information about who sent it and where it’s going. The most importantadvantageofbreakingdataintoindividuallyaddressedpacketsisthatpackets from many ongoing exchanges can travel on one wire, which makes it much cheaper to build a network: many computers can share the same wire without interfering. (In contrast,whenyoumakealocaltelephonecallwithinthesameexchangeonatraditional phone line, you have essentially reserved a wire from your phone to the phone of the person you’re calling. When all the wires are in use, as sometimes happens during a major emergency or holiday, not everyone who picks up a phone will get a dial tone. If you stay on the line, you’ll eventually get a dial tone when a line becomes free. In some countries with worse phone service than the United States, it’s not uncommon to have to wait half an hour or more for a dial tone.) Another advantage of packets is that checksums can be used to detect whether a packet was damaged in transit. We’re still missing one important piece: some notion of what computers need to say to pass data back and forth. A protocol is a precise set of rules defining how computers communicate: the format of addresses, how data is split into packets, and so on. There are many different protocols defining different aspects of network communication. For example, the Hypertext Transfer Protocol (HTTP) defines how web browsers and Networks | 3
servers communicate; at the other end of the spectrum, the IEEE 802.3 standard defines a protocol for how bits are encoded as electrical signals on a particular type of wire. Open, published protocol standards allow software and equipment from different ven‐ dors to communicate with one another. A web server doesn’t care whether the client is a Unix workstation, an Android phone, or an iPad, because all clients speak the same HTTP protocol regardless of platform. The Layers of a Network Sending data across a network is a complex operation that must be carefully tuned to the physical characteristics of the network as well as the logical character of the data being sent. Software that sends data across a network must understand how to avoid collisions between packets, convert digital data to analog signals, detect and correct errors, route packets from one host to another, and more. The process is further com‐ plicated when the requirement to support multiple operating systems and heterogene‐ ous network cabling is added. To hide most of this complexity from the application developer and end user, the dif‐ ferent aspects of network communication are separated into multiple layers. Each layer represents a different level of abstraction between the physical hardware (i.e., the wires and electricity) and the information being transmitted. In theory, each layer only talks to the layers immediately above and immediately below it. Separating the network into layers lets you modify or even replace the software in one layer without affecting the others, as long as the interfaces between the layers stay the same. Figure 1-1 shows a stack of possible protocols that may exist in your network. While the middle layer protocols are fairly consistent across most of the Internet today, the top and the bottom vary a lot. Some hosts use Ethernet; some use WiFi; some use PPP; some use something else. Similarly, what’s on the top of the stack will depend completely on which programs a host is running. The key is that from the top of the stack, it doesn’t really matter what’s on the bottom and vice versa. The layer model decouples the ap‐ plication protocols (the main subject of this book) from the physics of the network hardware and the topology of the network connections. 4 | Chapter 1: Basic Network Concepts
Figure 1-1. Protocols in different layers of a network There are several different layer models, each organized to fit the needs of a particular kind of network. This book uses the standard TCP/IP four-layer model appropriate for the Internet, shown in Figure 1-2. In this model, applications like Firefox and Warcraft run in the application layer and talk only to the transport layer. The transport layer talks only to the application layer and the Internet layer. The Internet layer in turn talks only to the host-to-network layer and the transport layer, never directly to the application layer. The host-to-network layer moves the data across the wires, fiber-optic cables, or other medium to the host-to-network layer on the remote system, which then moves the data up the layers to the application on the remote system. Figure 1-2. The layers of a network For example, when a web browser sends a request to a web server to retrieve a page, the browser is actually talking to the transport layer on the local client machine. The trans‐ The Layers of a Network | 5
port layer breaks the request into TCP segments, adds some sequence numbers and checksumstothedata,andthenpassestherequesttothelocalinternetlayer.Theinternet layer fragments the segments into IP datagrams of the necessary size for the local net‐ work and passes them to the host-to-network layer for transmission onto the wire. The host-to-network layer encodes the digital data as analog signals appropriate for the particular physical medium and sends the request out the wire where it will be read by the host-to-network layer of the remote system to which it’s addressed. The host-to-network layer on the remote system decodes the analog signals into digital data, then passes the resulting IP datagrams to the server’s internet layer. The internet layer does some simple checks to see that the IP datagrams aren’t corrupt, reassembles them if they’ve been fragmented, and passes them to the server’s transport layer. The server’stransportlayercheckstoseethatallthedataarrivedandrequestsretransmission of any missing or corrupt pieces. (This request actually goes back down through the server’s internet layer, through the server’s host-to-network layer, and back to the client system, where it bubbles back up to the client’s transport layer, which retransmits the missing data back down through the layers. This is all transparent to the application layer.) Once the server’s transport layer has received enough contiguous, sequential datagrams, it reassembles them and writes them onto a stream read by the web server running in the server application layer. The server responds to the request and sends its response back down through the layers on the server system for transmission back across the Internet and delivery to the web client. As you can guess, the real process is much more elaborate. The host-to-network layer is by far the most complex, and a lot has been deliberately hidden. For example, it’s entirely possible that data sent across the Internet will pass through several routers and their layers before reaching its final destination. It may need to be converted from radio waves in the air to electrical signals in copper wire to light pulses in fiber-optic cables and back again, possibly more than once. However, 90% of the time your Java code will work in the application layer and only need to talk to the transport layer. The other 10% of the time, you’ll be in the transport layer and talking to the application layer or the internet layer. The complexity of the host-to-network layer is hidden from you; that’s the point of the layer model. 6 | Chapter 1: Basic Network Concepts
Exploring the Variety of Random Documents with Different Content
FAITH i ss man has taken from me the form of his being and the manner of his speech. What to thee is evil, to another is good, to thee it is poison, to another it is sweet honey. To me words are nothing. I look into the heart of man." VII The Persian poet, Mohammed Roumi, who lived in the thirteenth century, is the author of the celebrated poem " Masnava." It contains some remarkable verses on prayer which are worthy of a trusting soul : — " A certain man cried out in the silence of the night, • Oh, Allah ! ' But Satan answered, ' Be silent, thou fool, thou hast babbled enough already ! Thou wilt never hear an answer from the height of the throne, however much thou mayst cry " Allah ! " and look disheartened.' " The man's heart was troubled, and he hung his head. Then appeared to him the prophet Kisr, and asked : ' Why hast thou ceased to call on God, and repented of thy prayers ? ' The man answered, ' I got no answer from Allah ; I heard no voice saying, " I am here," and I fear that the gates of salvation are shut against me.' Kisr answered, ' Thus has Allah commanded me, " Go thou to him and say, ' Oh, man, tried by much, have I not commanded thee to serve me ; have I not commanded thee to call on me. And my reply, " Here am I " is the same as thine " Oh, Allah ! " Thy suffering, thy ardour, and thy zeal, all these are my messengers to thee : when
156 REFLECTIONS OF A RUSSIAN STATESMAN thou strugglest with thyself and cryest for help, by this struggle and cry I draw thee to myself, and answer thy prayer. Thy fear and thy love are the signs of my forgiveness, and in thy words, "O Allah ! " is a multitude of answers, " I am with thee." ' "
THE IDEALS OF UNBELIEF The ancient words, " The fool hath said in his heart, there is no God," apply with especial force to- day. Their truth is plainer than the sun, although now all " progressive minds " are possessed by a passionate desire to live without God, to conceal Him, to deny His presence. Even men at heart benevolent and honourable ask themselves how they may realise benevolence, honour, and conscience without God. The Government of France, in the last stage of political disintegration, has organised its national schools without God. Among us, unhappily, certain representatives of intelligence have rivalled the Moscow princess, who said, " Ah, France, no better country in the world ! " — for not long ago a celebrated schoolmaster pointed out the French scholastic system as a model worthy of imitation. Among the latest books officially prescribed for study in the female schools of France is one entitled, " Instruction Morale et Civique des Jeunes Filles." This is in the nature of a secular catechism of morals, appointed to replace the study of the Word of God. This book is worthy of notice. It is divided into three sections, each bearing a different title. The first is composed of certain moral precepts on duty, honesty, conscience, and so forth. The second part iS7
158 REFLECTIONS OF A RUSSIAN STATESMAN contains a short description of the State and of the national institutions. The third part treats of woman, her mission, faculties, and virtues. The matter in the book is concise, simple, and clear, written as a textbook ought to be with a multitude of clear examples and illustrations. No exception can be taken to the manner of this book ; it preaches order, good morals, purity of thought and intention, kind deeds ; it approves with emphasis the sentiment and recognition of duty, and carefully sets forth a woman's duties in social and domestic life. One thing alone is notable. On no single page is mentioned the name of God, nor is there the slightest reference to the religious feeling. The author, after explaining the great importance of the part played in man by conscience, defines it thus : " Conscience is our conception of the opinion which others ..have about us and our actions" {consideration de Vopinion des antres). On this treacherous and mutable base, the opinion of others, is affirmed the moral foundation of our lives. How excellently this illustrates the ancient proverb, " Who thinks himself too wise becomes a fool." Unhappily, to this stream of idiotcy flooding France to-day are drawn even from our poor Russia little rills of native intelligence ; and in our newspapers and gazettes, in our leading articles and feuilletons are repeated in chorus the words of the Moscow princess. To the same chorus too often are drawn those well-meaning, but simple and inexperienced men, who fancy newspapers must bring to them some " new word " of civilisation. Nothing is more deplorable than the reasoning on
THE IDEALS OF UNBELIEF 159 the subject of education of our journalist critics, who tell us that while religion and religious training are indispensable, churches and ministers must be abolished. Sometimes they speak more plainly. " We do not reject religious teaching, we even demand it ; we cannot understand education without it ; but we object to Clericalism." By this term we must understand the Church and everything appertaining thereto. This Jesuitical casuistry, which the apostles of popular education have made peculiarly their own, misleads many readers who cannot appreciate subtlety in writing. These good men do not know that the word religion, as many other words, has changed its signification, and is made by many to imply something from which, if they but understood it, believers in God would recoil with abhorrence. They do not know that in our time religion may exist without God, and that the very word God, in its application by so-called men of science, has a double meaning. In 1882 appeared a remarkable book which awakened general interest. Therein the negation of God, by the enemies of all religion, was expressed with ferocity, with reckless and malicious irony, with a demand for the exclusive consideration of matter in the universe. The first part of the work expressed, in a tranquil tone, with dignity, with an ideal outlook on life, the whole teaching of the religion without God. This book was entitled "Natural Religion" (London, 1882). Its author, Professor Seeley of Oxford, was he whose former "Ecce Homo," which appeared ten years before, had attracted the attention, not only of men of
160 REFLECTIONS OF A RUSSIAN STATESMAN science, but of religious idealists who sought in it some new word on Christ and the Christian faith. A Russian translation of this latter work has been published by an admirer. But to the adherents of the Church Mr Seeley's work seemed strange and questionable. Few could look on it without distrust. This book contained an artistic analysis of the earthly life and character of Jesus Christ, treating exclusively of his human nature. It was written in a spirit of deep piety, in the language of philosophy, with occasional recourse to the terminology of theologians. The object of the "work seemed to be to hold up the image of Christ to pious imitation. The author, it seemed, was a Christian, full of religious feeling. But many religious readers took alarm, as if their views and sentiments of Christianity were not in accord with the views and sentiments of the author. The picture of Christ was a picture of supreme holiness, purity, and goodness, but not that picture which we have been taught to venerate from childhood — not the Christ honoured by the Christian Church. Something discordant appeared throughout the book, as if the author had either lost all faith, or was on the point of losing it. Nevertheless, the writer plainly affirmed his faith in the existence of a personal God ; in the immortality of the human soul ; in the Messianic significance of the appearance of Christ ; and even, although with some hesitation, in the reality of His miracles. Ten years passed ; again Mr Seeley appeared as the inspired prophet of religion, this time a new religion, and not the religion of Christ. The ancient
THE IDEALS OF UNBELIEF 161 revelation, he said, had done its work ; instead, a new revelation had come ; the naturalists, historians, and philologists of the age had borne us a revelation of which the ancient prophets had never dreamed. The Biblical criticism of German scholars was greater and more perfect than the Bible itself. With uncommon simplicity, turning to the believers and members of the Church, he asks : " Why should we quarrel, why should there be strife between us? We may unite in a single faith. We, men of science, also trust in God. Our God is Nature, which in one sense is a revelation too. Therefore we are not -atheists," he repeats, " and the battle between us, men of science, and you, men of faith, is merely a battle of words. Is it not the same ? For us God is Nature, and the scientific theory of the universe is a theory of theism also. Nature is a force existing outside of us ; its law for us is absolute : there is the divinity which we adore." Is it not strange that the author, while rejecting the personal existence of God, at the same time protests with energy against the accusation of atheism, which he rejects and condemns? What is atheism, then? This question Mr Seeley answers with a tortuous subtlety which to a simple mind must seem insanity. "There is an atheism which is a mere speculative crotchet, and there is an atheism which is a great moral disease. . . . The purest form of such real atheism might be called by the general name of wilfulness. All human activity is a transaction with Nature. It is the arrangement of a compromise between what we want on the one hand, and what Nature has decreed on the other. Not to recognise anything but your own will, to fancy anything within your reach if you only will strongly L
162 REFLECTIONS OF A RUSSIAN STATESMAN enough, to acknowledge no superior power outside yourself which must be considered, and in some way propitiated, if you would succeed in any undertaking : this is complete wilfulness, or, in other words, pure atheism." — Seeley, " Natural Religion," p. 27. To illustrate this obscure and disorderly argument, our author takes as example a country in its fate a symbol of pure atheism, and points to Poland. " Sedet aternumque sedebit" says he, " that unhappy Poland, not indeed extinguished, but partitioned, and every thirty years decimated anew, expiates the crime of atheistic wilfulness, the fatal pleasure of unbounded individual liberty, which rose up against the very nature of things." — Ibid. p. 29. Having disclosed this theory of religion, he describes in detail how the religious feeling is born from science, and, passing through the prism of imagination, is refracted in the moral nature of man into a religious trinity : the religion of Nature, the religion of Humanity, and the religion of Beauty. In this book, written with talent and spirit, is a doctrine by no means new, although for the first time expressed with such completeness. The reader finds there the well-known features of the Positivism so fashionable in our time — features familiar through the writings of Kant, George Eliot, and Herbert Spencer — the well-beloved of Russian translators. Not one of these writers exposes so clearly the internal weakness of this fashionable theory as the author of " Natural Religion." To what idiotcy must the mind have sunken when, drawn by the pride of self-adoration, it rejects the supernatural in life and nature, and strives to build a theory of life in relation to the universe. This theory is condemned to turn in an
THE IDEALS OF UNBELIEF 163 enchanted circle, and to contradict itself for ever. Denying a personal God, in vain it would sustain religion and establish an object of religious feeling; for, except the living God, there can be no object of religion. Rejecting the invisible world, the immortality of the soul, and the future life, it proclaims that the end of life is happiness, and would confine humanity within the limits of matter and of its earthly nature. Condemning revelation as invention or fantasy, and every dogma as falsehood, it seeks to support itself by a new dogma, proclaiming as an indisputable axiom the constant and endless progress of humanity. This theory, in a flash, reflects that wilfulness and that obduracy of thought which our author combines in his conception of atheism. It shows no sign of that clear and simple confidence which serves as a symptom of the truth and durability of doctrines. In their sermons on the happiness of humanity, its prophets all stumble on an actuality which they cannot deny. This actuality is the inevitable presence of evil and of evil works, of violence and of injustice in human life — the argument of pessimism. This argument cannot be lived down, although some of the apostles of Positivism strive to stifle its voice or hypocritically to ignore it, while others, more conscientious, stand by it with grief and questioning. To the number of the last belongs our author. While extolling the new religion of Nature, Humanity, and Beauty, and proving the strength and actuality of the cult it preaches, at the same time he admits that hardly have we found satisfaction in these ideas when pessimism raises its head
164 REFLECTIONS OF A RUSSIAN STATESMAN and brings us to despair. If it were not for pessimism, he declares, nothing would destroy our religious beliefs. And at the end of the book, when crowning his edifice, he makes these remarks : "The more our thoughts widen and deepen, as the universe grows upon us and we become accustomed to boundless space and time, the more petrifying is the contrast of our own insignificance, the more contemptible become the pettiness, shortness, fragility of the individual life. A moral paralysis creeps upon us. For a while we comfort ourselves with the notion of self-sacrifice ; we say, What matter if I pass, let me think of others ! But the other has become contemptible no less than the self; all human griefs alike seem little worth assuaging, human happiness too paltry at the best to be worth increasing. The whole moral world is reduced to a point ; the spiritual city, 'the goal of all the saints/ dwindles to the 'least of little stars'; good and evil, right and wrong, become infinitesimal, ephemeral matters, while eternity and infinity remain attributes of that only which is outside the realm of morality. Life becomes more intolerable the more we know and discover, so long as everything widens and deepens, except our own duration, and that remains as pitiful as ever. The affections die away in a world where everything great and enduring is cold ; they die of their own conscious feebleness and bloodlessness. "Supernatural Religion met this want by connecting Love and Righteousness with eternity. If it is shaken, how shall its place be supplied ? And what would Natural Religion avail then ? " Ibid. p. 261. Who would believe that these words were written by the ardent prophet of Natural Religion? Thus may a serious mind be entangled in the intellectual network it weaves. The essence of this work, with all its moderation of tone, with all the sincerity of its author, is a joyless paradox. That the various systems of cosmology, the scientific, the artistic, and the humanist, contain elements of religious feeling cannot be denied.
THE IDEALS OF UNBELIEF 165 But they do not embody the elements of a new faith, of a new church ; they are separate limbs — disjecta membra — of the Christian philosophy of life. Religion is impossible without the recognition of axiomatic truths unattainable by the path of induction. To such truths belong the existence of a personal God, and the immaterial nature of the human soul, whence springs supernaturalism, without which religion is inconceivable. With the exception of mathematics, scientific truths are by their nature hypothetical : they exist consciously only for scholars, and only by deception may be imparted to the mass in dogmatic form. This deception obtains among us and progresses — of this we find fresh evidence every day. II Intolerance of strange beliefs and strange opinions has never been so sharply expressed as it is nowadays by the apostles of radical and negative beliefs, among whom such intolerance is merciless and bitter, and joined with animosity and contempt. When we consider the relations of these teachers to the new doctrines they proclaim, their intolerance is more abhorrent than the old religious intolerance which expressed itself in sanguinary persecution. Then persecution was based on unqualified faith in a truth which absolutely existed. When men believe that they possess an absolute truth, sprung from the ultimate principle of life and involving happiness for all, as the Moslem believes in the Koran, it is conceivable that they may consider it a duty r
166 REFLECTIONS OF A RUSSIAN STATESMAN not only openly to preach their doctrine, but, if need be, by violence to enforce it upon others. But when it is merely an opinion, although it may be that nothing is more probable for him who formed it, how can we understand fanaticism so great that its advocate does not admit not only contradiction but even compromise, although conditional and temporary, with adverse opinion? Yet such passionate attachment to their own convictions or to the doctrines of their schools is an attribute to all the prophets of negation. Rejecting, as if it were not, the whole former history of the spiritual development of humanity, ignoring all ancient faiths and the spiritual conditions of peoples, denying all rights of independent existence, repelled not by the sanctity of personal faith, they claim admittance to every soul, and everywhere strive to establish their new religion. This they call the truth of their convictions. One of the representatives of the doctrine of Comte and the Positivists (John Morley "On Compromise") maintains that the first duty of every man to himself and to humanity is to solve in his heart the question, Does he or does he not believe in the existence of God ? Should he reach the conviction that faith in God is no better than a blind and unhealthy superstition, it is his sacred duty to break in with this conviction on every soul, to take advantage of every occasion to convert, firstly,his kinsmen and neighbours, and then, if possible, the people ; to proclaim it everywhere, and in private and public life wholly to renounce all forms and ceremonies which, directly or indirectly, express a faith opposed to his conviction. What is this but a terrible violence against the conscience of
THE IDEALS OF UNBELIEF 167 others — and in the name of what? In the name of a personal opinion. In this hell of vanity we can find neither love nor faith. But without love and without faith there can be no truth. How different to listen to the voice of the old true teacher ! What faith and love, what knowledge of the human soul is there in those words in which the Apostle to the Corinthians enjoins respect for human conscience. He knows the truth, but with his deep spiritual knowledge how cautiously would he approach the human soul ! His purpose is that the soul shall accept and embrace the new belief in the spirit of sincerity and truth by faith alone, without disunion, without discord with itself. All that comes not from faith is sin. And the Apostle teaches the strong and learned that they must spare the consciences of their weaker brethren even in superstition, when the soul is not ripe to accept the truth with entire faith. The Apostle, the herald of Christian freedom, acting from conviction, sacrifices freedom itself to the sanctity of conscience, knowing that conscience is dearer than all. You know, says he, that meat commendeth us not to God ; for neither if we eat are we the better ; neither if we eat not are we the worse. You know that the idol is nothing, that the false God does not exist, therefore with quiet conscience buy meat and eat it, which was brought as sacrifice to the idol. Ill Nothing is more surprising than the fatuity of clever men who have grown up in estrangement from
168 REFLECTIONS OF A RUSSIAN STATESMAN actual life, and who are blinded by confidence in the infallibility of logic. By adoration of reason they are seduced from religion, and at last incited to hatred of every faith in the only living God. But those who at the same time are men of conscience, find that they cannot rid themselves of the aspiration to faith innate in humanity ; those whose hearts are unhardened by the severity of logic admit the lawfulness of religious feeling in man, and strive to satisfy it by some religion devised by themselves. We may wonder at the fancifulness of plans contrived by minds apparently striving to drive away everything like fancy out of their reasoning and deliberations. Strauss, in his work on "The Old and the New Faith," while rejecting Christianity, speaks with enthusiasm of the religious sentiment, but as its object and centre replaces the living God with the idea of the World, the so-called Universum. After the death of Mill, his occasional thoughts on religion appeared in London under the title, " Three Essays on Religion : Nature, the Utility of Religion, and Theism." The utility of religion he admits without reserve, and, while rejecting Christianity, he speaks of the individual Christ with the greatest enthusiasm. "The value of religion to the individual, both in the past and present, as a source of personal satisfaction and of elevated feelings, is not to be disputed. But it has still to be considered whether, in order to obtain this good, it is necessary to travel beyond the boundaries of the world which we inhabit j or whether the idealisation of our earthly life, the cultivation of a high conception of what it may be made, is not capable of supplying a poetry, and, in the best sense of the word, a religion, equally fitted to exalt the feelings, and (with the same aid from education) still better calcu 
THE IDEALS OF UNBELIEF 169 lated to ennoble the conduct, than any belief respecting the unseen powers." "Three Essays on Religion" (Utility of Religion), pp. 104-5. London, 1874. The question is worthy of Mill as we know him by the history of his education. It is interesting to note how in his decision of this question, Mill could not, with Strauss, accept as decisive the idea of the Universe, for Mill, strange to say, did not trust in Nature. In the beginning of the same book, true as ever to his estrangement from reality, he speaks of " Enquiry into the truth of the doctrines which make Nature a test of right and wrong, good and evil, or which in any mode or degree attach merit or approval to following, imitating, or obeying Nature." — Ibid. (Nature), p. 13. These doctrines Mill rejects, for in Nature he sees blind force and nothing more. Nature inspires desires which it does not satisfy ; it builds great edifices, powers, and actions, in a moment to overthrow them ; it destroys blindly and indiscriminately all that it has created. For this reason Mill declines to construct on Nature any system of morals or of religion. What, then, does he think ? These are his own words : "When we consider how ardent a sentiment, in favourable circumstances of education, the love of country has become, we cannot judge it impossible that the love of that larger country, the world, may be nursed into similar strength, both as a source of elevated emotion and as a principle of duty. He who needs any other lesson on this subject than the whole course of ancient history affords, let him read Cicero De Officiis. It cannot be said that the standard of morals laid down in that celebrated treatise is a high standard. To our notions, it is on many points unduly lax, and admits capitu 
170 REFLECTIONS OF A RUSSIAN STATESMAN lations of conscience. But on the subject of duty to our country there is no compromise. That any man, with the smallest pretensions to virtue, could hesitate to sacrifice life, reputation, family, everything valuable to him, to the love of country, is a supposition which this eminent interpreter of Greek and Roman morality cannot entertain for a moment. If, then, persons could be trained, as we see they were, not only to believe in theory that the good of their country was an object to which all others ought to yield, but to feel this practically as the grand duty of life, so also may they be made to feel the same absolute obligation towards the universal good. A morality grounded on large and wise views of the whole, neither sacrificing the individual to the aggregate nor the aggregate to the individual, but giving to duty, on the one hand, and to freedom and spontaneity, on the other, their proper province, would derive its power in the superior natures from sympathy and benevolence and the passion for ideal excellence ; in the inferior, from the same feelings cultivated up to the measure of their capacity, with the superadded force of shame. This exalted morality would not depend for its ascendency on any hope of reward ; but the reward which might be looked for, and the thought of which would be a consolation in suffering, and a support in moments of weakness, would not be a problematical future existence, but the approbation in this of those whom we respect, and ideally of all those, dead or living, whom we admire or venerate. For, the thought that our dead parents or friends would have approved our conduct is a scarcely less powerful motive than the knowledge that our living ones do approve it ; and the idea that Socrates, or Howard or Washington, or Antoninus, or Christ, would have sympathised with us, or that we are attempting to do our part in the spirit in which they did theirs, has operated on the very best minds as a strong incentive to act up to their highest feelings and convictions. "To call these sentiments by the name of morality, exclusively of any other title, is claiming too little for them. They are a real religion 5 of which, as of other religions, outward good works (the utmost meaning usually suggested by the word morality) are
only a part, and are indeed rather the fruits of the religion than the religion itself. The essence of religion is the strong and earnest direction of the emotions and desires towards an ideal object, recognised as of the highest excellence, and as rightfully paramount
THE IDEALS OF UNBELIEF 171 over all selfish objects of desire. This condition is fulfilled by the Religion of Humanity in an eminent degree, and in as high a sense, as by the supernatural religions even in their best manifestations, and far more so than in any of their others." Ibid. (Utility of Religion), pp. 107-9. The foregoing words explain themselves. They show the narrowness, we should say rather the idiotcy, of human wisdom when it seeks an abstract conception of life and of humanity, while ignoring life itself, and rejecting the human soul. Such a religion may indeed be sufficient for thinkers like Mill, secluded from the world in abstract speculation, but how shall the people accept and understand it ? — the people, a living organism held in communion only by living sentiment and conscience, and repelled by abstractions and generalities. In the people, such a religion, if it bore fruit at all, would bear fruit in reversion to paganism. The people — which we cannot conceive detached from Nature — if it forgot the faith of its fathers, would again personify the idea, either of the universe, resolving it into separate forces, or of that humanity which stands as a binding spiritual principle, resolving it also into its representative spiritual forces ; and there would result so many false gods instead of one true God. It cannot be that we are condemned to suffer this?
THE NEW RELIGION AND THE NEW MARRIAGE We are told that our religion is drawing to its end, that a new faith will replace it, the dawn of which is on the point of appearing. God grant that this maybe delayed, and that, if it must come, it may not be for long ! For it will not be a time of enlightenment, but of darkness. The ancient faith contains all that human nature has of sincerity — the sincerity of direct sensations and conscience, the sincerity which, from the depths of our spiritual nature, corresponds to the words of divine revelation. This is a living truth, and its roots are sunken in the souls of all. Of it was it said : " Every one that is of the truth heareth my voice." The ancient faith was founded on the consciousness of every man of a living soul which is immortal and one, a living soul he confounds neither with Nature nor with humanity. By this ' he knows himself before God and before his fellow-men, by this he wishes to live eternally. By this he enters into the free alliance of love with others, and, as he lives in his soul, so he answers for it himself. Through this the existence of his Creator is revealed as simply as his own life, and by this simple feeling, independently of reason, he maintains his faith. The prophets of a new religion appear. Some laugh at the ancient faith, and would destroy it, 172
THE NEW RELIGION AND THE NEW MARRIAGE 173 without the will to create anew. Others appear more serious ; they seek supreme wisdom, and strive to impose on us a wisdom of their own. Each offers us his own conception of truth, his favourite system of religion, for all apprehend the necessity of religion, and each would create one himself. How pitiable are these creations I They lack the power to draw the living soul and inspire it with a living idea, for not one of them sets the living spirit of God in the centre of his faith. In recent times many various systems have appeared from the pens of philosophers, each at will attempting to construct for humanity a faith without God. Each would constitute his system on the basis of reason, by its nature an absurdity. For human reason in a straight path, ignoring and rejecting no facts of Nature or of the human soul, can never eliminate the idea of God. The true source of atheism is not in the mind but in the heart, for, as the prophet said, "The fool hath said in his heart, there is no God." In the heart, that is, in the will, is the source of all error, however reason may seek to explain it. Error is born by the desire of the heart for full freedom, by rebellion against the commandments, and against Him who is the beginning and the end of all commandments. To free oneself of the commandments, there is no other path than to reject their supreme authority, and to replace it by the authority of self. The oldest of human histories is repeated from generation to generation, " Ye shall be as gods, knowing good and evil." This has been the source of atheism from immemorial time. It is wonderful, indeed, how reason deceives itself.
174 REFLECTIONS OF A RUSSIAN STATESMAN Without God it seems that there can be no religion, yet such a religion is proclaimed by atheists. They say, " In the place of these outworn tales of God let us put the truth. God is nowhere visible, while Nature and humanity are actual facts. Humanity is not only a fact, it is a force able, by the paths of reason and experience, to attain in the course of centuries unimaginable perfection. This idea of progression contains such internal force and profundity that it is enough to compensate man for religious sentiment, and to bind the race in the universal religion of humanity." Is this not the Biblical, " Ye shall be as gods " ? Such are the doctrines of modern Positivist science, and of the so-called Utilitarianism. From another side appears the celebrated apostle of the Tubingen school, the pillar of Biblical criticism, who lived to an old age in denial of the historic foundation of Christianity. This is Dr Strauss, the author of the " Life of Jesus " ; the author of " The Old and the New Religion," in which he himself says he has made his confession, and given to the world the result of all his learned labours and philosophical speculations on God, on Nature, and on humanity. In youth, in the " Life of Jesus," he undertook, with some respect and caution, the analysis of those facts consecrated by the traditional belief of man, touching with tenderness the fundamental ideas of faith. In this work is seen a remnant of respect for God. But later we find a furious irritation against the Godhead, as a false and pernicious fable which has corrupted the minds of mankind. But while rejecting God, by a strange incon 
THE NEW RELIGION AND THE NEW MARRIAGE 175 sistency of thought, he does not abandon the religious feeling. In himself he feels the necessity, and affirms the existence, of religious devotion. What is the object of this devotion, which at the same time has power to possess and inspire the soul ? Not a personal divinity which exists not, but the world {Uftiversum) which constitutes the source of all good and power — which exists by the law of pure reason. We demand, he says, for this Universe the same devout feeling as a good man of the ancient faith cherished towards God. What is this Universe, and what its spiritual element? Answering that question, Strauss reveals himself as a disciple of the Positivist philosophy, and of the new materialism. The doctrine of Kant and of Laplace on the exclusive activity of mechanical forces in the planetary system, he applies absolutely to all the phenomena of animal and spiritual life ; he regards the soul of man as nothing better than the result of the complex interaction of mechanical forces. The soul as a spiritual essence Strauss rejects. As might be expected, he accepts triumphantly the theories of Darwin on the Origin of Species, limiting not their application to the phenomena of the external world, but extending them capriciously to all the manifestations of life. The imperfection and inconsistency of Darwin's reasonings do not alarm him in the least. All doubt is eliminated by his new religion, by faith in his own hypothesis, incompatible, he tells us, with the existence of God. It matters not that such abstract hypotheses as spontaneous generation remain unproven. He cannot say how or when, but without doubt some day they
REFLEC70NS OF A RUSSIAN STATESMAN will be prove. In considering the origin of man, he does not rouble to explain and reconcile the origin of his intellectual powers, his moral ideas, and his aesthcic conceptions. All is explained by the magic wois, "Natural Selection." Surely, if this capricious inituation with theory constitutes the new religion, hat religion is nothing better than a new superstitm. The doctrie of Darwin could not have appeal at a time mre opport new religion. It enlighu it gave ther. the keystc crown the valt of their his teaching with eagerne that the anent faith wa annihilated. From every apply his pnciples to all life, deducin conclusions Darwin neve dreamed, pupils out-cstanced the ma near when tey will condemn Meantime, te doctrines of application ■> the facts from hardly justif those apprehensio the faith wich they awakened herents. Th system of Galile Newton, all ew discoveries in ge their day aakei more agitati the faith ofl in no will it be " these are nt re and the firsfcnthusic to wane. Tey are ac the prophets of with a new 1 they sougl They seized then proc :rthrohast lena it /
Welcome to our website – the ideal destination for book lovers and knowledge seekers. With a mission to inspire endlessly, we offer a vast collection of books, ranging from classic literary works to specialized publications, self-development books, and children's literature. Each book is a new journey of discovery, expanding knowledge and enriching the soul of the reade Our website is not just a platform for buying books, but a bridge connecting readers to the timeless values of culture and wisdom. With an elegant, user-friendly interface and an intelligent search system, we are committed to providing a quick and convenient shopping experience. Additionally, our special promotions and home delivery services ensure that you save time and fully enjoy the joy of reading. Let us accompany you on the journey of exploring knowledge and personal growth! ebookname.com

Java Network Programming Fourth Edition Elliotte Rusty Harold

  • 1.
    Java Network ProgrammingFourth Edition Elliotte Rusty Harold install download https://ebookname.com/product/java-network-programming-fourth- edition-elliotte-rusty-harold/ Get the full ebook with Bonus Features for a Better Reading Experience on ebookname.com
  • 2.
    Instant digital products(PDF, ePub, MOBI) available Download now and explore formats that suit you... XML in a nutshell 3rd ed Edition Elliotte Rusty Harold https://ebookname.com/product/xml-in-a-nutshell-3rd-ed-edition- elliotte-rusty-harold/ Linear programming and network flows Fourth Edition M. S. Bazaraa https://ebookname.com/product/linear-programming-and-network- flows-fourth-edition-m-s-bazaraa/ Java Programming 5th Edition Joyce Farrell https://ebookname.com/product/java-programming-5th-edition-joyce- farrell/ Scott 2007 Standard Postage Stamp Catalogue Vol 6 Countries of the World So Z 163rd Edition James E. Kloetzel https://ebookname.com/product/scott-2007-standard-postage-stamp- catalogue-vol-6-countries-of-the-world-so-z-163rd-edition-james- e-kloetzel/
  • 3.
    601 great scrapbookideas 1st ed Edition Memory Makers Books https://ebookname.com/product/601-great-scrapbook-ideas-1st-ed- edition-memory-makers-books/ On Percs Facebooking While Intoxicated 1st Edition Mike Rainey https://ebookname.com/product/on-percs-facebooking-while- intoxicated-1st-edition-mike-rainey/ If Not Now When Writings in Defense of Europe 1st Edition Mathijs Koenraadt https://ebookname.com/product/if-not-now-when-writings-in- defense-of-europe-1st-edition-mathijs-koenraadt/ Research for Development A Practical Guide 1st Edition Sophie Laws https://ebookname.com/product/research-for-development-a- practical-guide-1st-edition-sophie-laws/ A Slice of Organic Life 1st Edition Sheherazade Goldsmith https://ebookname.com/product/a-slice-of-organic-life-1st- edition-sheherazade-goldsmith/
  • 4.
    Handbook of Diabetes4th Edition Rudy Bilous https://ebookname.com/product/handbook-of-diabetes-4th-edition- rudy-bilous/
  • 7.
    Elliotte Rusty Harold FOURTHEDITION Java Network Programming
  • 8.
    Java Network Programming,Fourth Edition by Elliotte Rusty Harold Copyright © 2014 Elliotte Rusty Harold. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use. Online editions are alsoavailableformosttitles(http://my.safaribooksonline.com).Formoreinformation,contactourcorporate/ institutional sales department: 800-998-9938 or corporate@oreilly.com. Editor: Meghan Blanchette Production Editor: Nicole Shelby Copyeditor: Kim Cofer Proofreader: Jasmine Kwityn Indexer: Judy McConville Cover Designer: Randy Comer Interior Designer: David Futato Illustrator: Rebecca Demarest October 2013: Fourth Edition Revision History for the Fourth Edition: 2013-09-23: First release See http://oreilly.com/catalog/errata.csp?isbn=9781449357672 for release details. Nutshell Handbook, the Nutshell Handbook logo, and the O’Reilly logo are registered trademarks of O’Reilly Media, Inc. Java Network Programming, the image of a North American river otter, and related trade dress are trademarks of O’Reilly Media, Inc. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and O’Reilly Media, Inc., was aware of a trade‐ mark claim, the designations have been printed in caps or initial caps. While every precaution has been taken in the preparation of this book, the publisher and author assume no responsibility for errors or omissions, or for damages resulting from the use of the information contained herein. ISBN: 978-1-449-35767-2 [LSI]
  • 9.
    This book isdedicated to my dog, Thor.
  • 11.
    Table of Contents Preface.. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii 1. Basic Network Concepts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Networks 2 The Layers of a Network 4 The Host-to-Network Layer 7 The Internet Layer 8 The Transport Layer 9 The Application Layer 10 IP, TCP, and UDP 10 IP Addresses and Domain Names 11 Ports 13 The Internet 14 Internet Address Blocks 15 Network Address Translation 15 Firewalls 15 Proxy Servers 16 The Client/Server Model 18 Internet Standards 19 IETF RFCs 20 W3C Recommendations 22 2. Streams. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 Output Streams 26 Input Streams 31 Marking and Resetting 34 Filter Streams 35 Chaining Filters Together 37 Buffered Streams 38 v
  • 12.
    PrintStream 39 Data Streams41 Readers and Writers 44 Writers 45 OutputStreamWriter 47 Readers 47 Filter Readers and Writers 49 PrintWriter 51 3. Threads. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53 Running Threads 55 Subclassing Thread 56 Implementing the Runnable Interface 58 Returning Information from a Thread 60 Race Conditions 61 Polling 63 Callbacks 63 Futures, Callables, and Executors 68 Synchronization 70 Synchronized Blocks 72 Synchronized Methods 74 Alternatives to Synchronization 75 Deadlock 77 Thread Scheduling 78 Priorities 78 Preemption 79 Thread Pools and Executors 89 4. Internet Addresses. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 The InetAddress Class 95 Creating New InetAddress Objects 95 Getter Methods 100 Address Types 102 Testing Reachability 106 Object Methods 106 Inet4Address and Inet6Address 107 The NetworkInterface Class 108 Factory Methods 108 Getter Methods 110 Some Useful Programs 111 SpamCheck 111 vi | Table of Contents
  • 13.
    Processing Web ServerLogfiles 112 5. URLs and URIs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 URIs 117 URLs 120 Relative URLs 122 The URL Class 123 Creating New URLs 123 Retrieving Data from a URL 128 Splitting a URL into Pieces 135 Equality and Comparison 139 Conversion 141 The URI Class 141 Constructing a URI 142 The Parts of the URI 144 Resolving Relative URIs 147 Equality and Comparison 148 String Representations 149 x-www-form-urlencoded 149 URLEncoder 150 URLDecoder 154 Proxies 154 System Properties 155 The Proxy Class 155 The ProxySelector Class 156 Communicating with Server-Side Programs Through GET 157 Accessing Password-Protected Sites 161 The Authenticator Class 162 The PasswordAuthentication Class 164 The JPasswordField Class 164 6. HTTP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169 The Protocol 169 Keep-Alive 175 HTTP Methods 177 The Request Body 179 Cookies 181 CookieManager 184 CookieStore 185 7. URLConnections. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187 Opening URLConnections 188 Table of Contents | vii
  • 14.
    Reading Data froma Server 189 Reading the Header 190 Retrieving Specific Header Fields 191 Retrieving Arbitrary Header Fields 197 Caches 199 Web Cache for Java 203 Configuring the Connection 208 protected URL url 209 protected boolean connected 209 protected boolean allowUserInteraction 210 protected boolean doInput 211 protected boolean doOutput 212 protected boolean ifModifiedSince 212 protected boolean useCaches 214 Timeouts 215 Configuring the Client Request HTTP Header 215 Writing Data to a Server 218 Security Considerations for URLConnections 223 Guessing MIME Media Types 224 HttpURLConnection 224 The Request Method 225 Disconnecting from the Server 229 Handling Server Responses 230 Proxies 235 Streaming Mode 235 8. Sockets for Clients. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237 Using Sockets 237 Investigating Protocols with Telnet 238 Reading from Servers with Sockets 240 Writing to Servers with Sockets 246 Constructing and Connecting Sockets 251 Basic Constructors 251 Picking a Local Interface to Connect From 253 Constructing Without Connecting 254 Socket Addresses 255 Proxy Servers 256 Getting Information About a Socket 257 Closed or Connected? 258 toString() 259 Setting Socket Options 259 TCP_NODELAY 260 viii | Table of Contents
  • 15.
    SO_LINGER 261 SO_TIMEOUT 261 SO_RCVBUFand SO_SNDBUF 262 SO_KEEPALIVE 263 OOBINLINE 264 SO_REUSEADDR 265 IP_TOS Class of Service 265 Socket Exceptions 267 Sockets in GUI Applications 268 Whois 269 A Network Client Library 272 9. Sockets for Servers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283 Using ServerSockets 283 Serving Binary Data 288 Multithreaded Servers 289 Writing to Servers with Sockets 293 Closing Server Sockets 295 Logging 297 What to Log 297 How to Log 298 Constructing Server Sockets 302 Constructing Without Binding 304 Getting Information About a Server Socket 305 Socket Options 306 SO_TIMEOUT 307 SO_REUSEADDR 308 SO_RCVBUF 308 Class of Service 309 HTTP Servers 309 A Single-File Server 310 A Redirector 314 A Full-Fledged HTTP Server 319 10. Secure Sockets. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325 Secure Communications 326 Creating Secure Client Sockets 328 Choosing the Cipher Suites 332 Event Handlers 336 Session Management 336 Client Mode 338 Creating Secure Server Sockets 339 Table of Contents | ix
  • 16.
    Configuring SSLServerSockets 343 Choosingthe Cipher Suites 343 Session Management 344 Client Mode 344 11. Nonblocking I/O. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347 An Example Client 349 An Example Server 353 Buffers 359 Creating Buffers 361 Filling and Draining 363 Bulk Methods 364 Data Conversion 365 View Buffers 368 Compacting Buffers 370 Duplicating Buffers 372 Slicing Buffers 376 Marking and Resetting 377 Object Methods 377 Channels 378 SocketChannel 378 ServerSocketChannel 381 The Channels Class 383 Asynchronous Channels (Java 7) 384 Socket Options (Java 7) 386 Readiness Selection 388 The Selector Class 388 The SelectionKey Class 390 12. UDP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393 The UDP Protocol 393 UDP Clients 395 UDP Servers 397 The DatagramPacket Class 399 The Constructors 401 The get Methods 403 The setter Methods 406 The DatagramSocket Class 408 The Constructors 409 Sending and Receiving Datagrams 411 Managing Connections 416 Socket Options 417 x | Table of Contents
  • 17.
    SO_TIMEOUT 417 SO_RCVBUF 418 SO_SNDBUF419 SO_REUSEADDR 419 SO_BROADCAST 419 IP_TOS 420 Some Useful Applications 421 Simple UDP Clients 421 UDPServer 425 A UDP Echo Client 428 DatagramChannel 431 Using DatagramChannel 431 13. IP Multicast. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443 Multicasting 444 Multicast Addresses and Groups 447 Clients and Servers 450 Routers and Routing 452 Working with Multicast Sockets 453 The Constructors 454 Communicating with a Multicast Group 455 Two Simple Examples 460 Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465 Table of Contents | xi
  • 19.
    Preface Java’s growth overthe 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 com‐ mon 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 Program‐ ming exposes the power and sophistication of this library. This book’s goal is to enable xiii
  • 20.
    you to startusing Java as a platform for serious network programming. To do so, this book provides a general background in network fundamentals, as well as detailed dis‐ cussions 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, AsynchronousSocketChan nel, 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 pre‐ vious one. Organization of the Book Chapter1,Basic Network Concepts,explainsindetailwhataprogrammerneedstoknow about how the networks and the Internet work. It covers the protocols that underlie the Internet, such as TCP/IP and UDP/IP. xiv | Preface
  • 21.
    The next twochapters 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. ExperiencedJavaprogrammersmaybeabletoskimorskipthesetwochapters.However, Chapter 4, Internet Addresses, is essential reading for everyone. It shows how Java pro‐ grams 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 chap‐ ter, 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 down‐ loadinginformationandfilesfromnetworkserversofmanykinds.TheURLclassenables 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 communica‐ tions 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. Preface | xv
  • 22.
    Chapter 12, UDP,introduces the User Datagram Protocol (UDP) and the associated DatagramPacket and DatagramSocket classes that provide fast, unreliable communi‐ cation. 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 en‐ vironment, 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 syntaxofJava.Youshouldhavewrittensimpleapplications.Italsowouldn’thurtifyou’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 net‐ work 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 pro‐ gramming. You should find it a complete introduction to networking concepts and network application development. I don’t assume that you have a few thousand net‐ working 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 xvi | Preface
  • 23.
    relatively minor. Youshouldn’t have any trouble using this book after Java 8 is released. New APIs, however, have been somewhat more frequent in the supporting classes, par‐ ticularly 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 com‐ plete 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 exces‐ sively 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 ap‐ parent 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.cafeau lait.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. Preface | xvii
  • 24.
    Conventions Used inThis 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) Indicates a tip, suggestion, or general note. 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); xviii | Preface
  • 25.
    When code ispresented 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!). Request for Comments I enjoy hearing from readers, whether with general comments about this book, specific corrections, other topics they would like to see covered, or just war stories about their own network programming travails. You can reach me by sending an email to elharo@ibiblio.org.Pleaserealize,however,thatIreceiveseveralhundredpiecesofemail a day and cannot personally respond to each one. For the best chance of getting a per‐ sonal response, please identify yourself as a reader of this book. If you have a question about a particular program that isn’t working as you expect, try to reduce it to the simplest case that reproduces the bug, preferably a single class, and paste the text of the entire program into the body of your email. Unsolicited attachments will be deleted unopened. And please, please send the message from the account you want me to reply to and make sure that your Reply-to address is properly set! There’s nothing quite so frustrating as spending an hour or more carefully researching the answer to an inter‐ esting question and composing a detailed response, only to have it bounce because my correspondentsentherfeedbackfromapublicterminalandneglectedtosetthebrowser preferences to include her actual email address. I also adhere to the old saying “If you like this book, tell your friends. If you don’t like it, tell me.” I’m especially interested in hearing about mistakes. This is the fourth edition. I’ve yet to make it perfect, but I keep trying. As hard as I and the editors at O’Reilly Preface | xix
  • 26.
    workedonthisbook,I’msuretherearemistakesandtypographicalerrorsthatwemissed here somewhere. AndI’m sure that at least one of them is a really embarrassing whopper of a problem. If you find a mistake or a typo, please let me know so I can correct it. I’ll post it on the O’Reilly website at http://oreil.ly/java_np_errata. Before reporting errors, please check one of those pages to see if I already know about it and have posted a fix. Any errors that are reported will be fixed in future printings. Using Code Examples This book is here to help you get your job done. In general, if this book includes code examples, you may use the code in this book in your programs and documentation. You do not need to contact us for permission unless you’re reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from this book does not require permission. Selling or distributing a CD-ROM of examples from O’Reilly books does require permission. Answering a question by citing this book and quoting example code does not require permission. Incorporating a significant amount of example code from this book into your product’s documentation does require per‐ mission. We appreciate, but do not require, attribution. An attribution usually includes the title, author,publisher,andISBN.Forexample:“JavaNetworkProgramming,FourthEdition, by Elliotte Rusty Harold (O’Reilly). Copyright 2014 Elliotte Rusty Harold, 978-1-449-35767-2.” If you feel your use of code examples falls outside fair use or the permission given here, feel free to contact us at permissions@oreilly.com. Safari® Books Online Safari Books Online is an on-demand digital library that delivers expert content in both book and video form from the world’s lead‐ ing authors in technology and business. Technology professionals, software developers, web designers, and business and crea‐ tive professionals use Safari Books Online as their primary resource for research, prob‐ lem solving, learning, and certification training. Safari Books Online offers a range of product mixes and pricing programs for organi‐ zations, government agencies, and individuals. Subscribers have access to thousands of books, training videos, and prepublication manuscripts in one fully searchable database from publishers like O’Reilly Media, Prentice Hall Professional, Addison-Wesley Pro‐ fessional, Microsoft Press, Sams, Que, Peachpit Press, Focal Press, Cisco Press, John Wiley & Sons, Syngress, Morgan Kaufmann, IBM Redbooks, Packt, Adobe Press, FT Press, Apress, Manning, New Riders, McGraw-Hill, Jones & Bartlett, Course Technol‐ xx | Preface
  • 27.
    ogy, and dozensmore. For more information about Safari Books Online, please visit us online. How to Contact Us Please address comments and questions concerning this book to the publisher: O’Reilly Media, Inc. 1005 Gravenstein Highway North Sebastopol, CA 95472 800-998-9938 (in the United States or Canada) 707-829-0515 (international or local) 707-829-0104 (fax) We have a web page for this book, where we list errata, examples, and any additional information. You can access this page at http://oreil.ly/java-network-prgamming. To comment or ask technical questions about this book, send email to bookques tions@oreilly.com. For more information about our books, courses, conferences, and news, see our website at http://www.oreilly.com. Find us on Facebook: http://facebook.com/oreilly Follow us on Twitter: http://twitter.com/oreillymedia Watch us on YouTube: http://www.youtube.com/oreillymedia Acknowledgments Many people were involved in the production of this book. My editor, Mike Loukides, gotthingsrolling,andprovidedmanyhelpfulcommentsalongthewaythatsubstantially improved the book. Dr. Peter “Peppar” Parnes helped out immensely with Chapter 13. The technical editors all provided invaluable assistance in hunting down errors and omissions. Simon St. Laurent provided crucial advice on which topics deserved more coverage. Scott Oaks lent his thread expertise to Chapter 3, proving once again by the many subtle bugs he hunted down that multithreading still requires the attention of an expert. Ron Hitchens shone light into many of the darker areas of the new I/O APIs. Marc Loy and Jim Elliott reviewed some of the most bleeding edge material in the book. Timothy F. Rohaly was unswerving in his commitment to making sure I closed all my socketsandcaughtallpossibleexceptions,andingeneralwrotethecleanest,safest,most exemplary code I could write. John Zukowski found numerous errors of omission, all nowfilledthankstohim.Andtheeagle-eyedAvnerGelbdisplayedanastonishingability to spot mistakes that had somehow managed to go unnoticed by myself, all the other Preface | xxi
  • 28.
    editors, and thetens of thousands of readers of the first edition. Alex Stangl and Ryan Cuprak provided further assistance with spotting both new and lingering mistakes in this latest edition. It isn’t customary to thank the publisher, but the publisher does set the tone for the rest of the company, authors, editors, and production staff alike; and I think Tim O’Reilly deserves special credit for making O’Reilly Media absolutely one of the best houses an author can write for. If there’s one person without whom this book would never have been written, it’s him. If you, the reader, find O’Reilly books to be consistently better than most of the dreck on the market, the reason really can be traced straight back to Tim. My agent, David Rogelberg, convinced me it was possible to make a living writing books like this rather than working in an office. The entire crew at ibiblio.org over the last several years has really helped me to communicate better with my readers in a variety of ways. Every reader who sent in bouquets and brickbats for previous editions has been instrumental in helping me write this much-improved edition. All these people deserve much thanks and credit. Finally, as always, I’d like to offer my largest thanks to my wife, Beth, without whose love and support this book would never have happened. —Elliotte Rusty Harold elharo@ibiblio.org July 5, 2013 xxii | Preface
  • 29.
    CHAPTER 1 Basic NetworkConcepts Network programming is no longer the province of a few specialists. It has become a core part of every developer’s toolbox. Today, more programs are network aware than aren’t. Besides classic applications like email, web browsers, and remote login, most major applications have some level of networking built in. For example: • Text editors like BBEdit save and open files directly from FTP servers. • IDEs like Eclipse and IntelliJ IDEA communicate with source code repositories like GitHub and Sourceforge. • Word processors like Microsoft Word open files from URLs. • Antivirus programs like Norton AntiVirus check for new virus definitions by con‐ necting to the vendor’s website every time the computer is started. • Music players like Winamp and iTunes upload CD track lengths to CDDB and download the corresponding track titles. • Gamers playing multiplayer first-person shooters like Halo gleefully frag each other in real time. • Supermarket cash registers running IBM SurePOS ACE communicate with their store’s server in real time with each transaction. The server uploads its daily receipts to the chain’s central computers each night. • Schedule applications like Microsoft Outlook automatically synchronize calendars among employees in a company. Java was the first programming language designed from the ground up for network applications. Java was originally aimed at proprietary cable television networks rather than the Internet, but it’s always had the network foremost in mind. One of the first two real Java applications was a web browser. As the Internet continues to grow, Java is uniquely suited to build the next generation of network applications. 1
  • 30.
    One of thebiggest secrets about Java is that it makes writing network programs easy. In fact, it is far easier to write network programs in Java than in almost any other language. This book shows you dozens of complete programs that take advantage of the Internet. Some are simple textbook examples, while others are completely functional applica‐ tions. One thing you’ll notice in the fully functional applications is just how little code is devoted to networking. Even in network-intensive programs like web servers and clients, almost all the code handles data manipulation or the user interface. The part of the program that deals with the network is almost always the shortest and simplest. In brief, it is easy for Java applications to send and receive data across the Internet. This chapter covers the background networking concepts you need to understand be‐ fore writing networked programs in Java (or, for that matter, in any language). Moving from the most general to the most specific, it explains what you need to know about networks in general, IP and TCP/IP-based networks in particular, and the Internet. This chapter doesn’t try to teach you how to wire a network or configure a router, but you will learn what you need to know to write applications that communicate across the Internet.Topicscoveredinthischapterincludethenatureofnetworks;theTCP/IPlayer model; the IP, TCP, and UDP protocols; firewalls and proxy servers; the Internet; and the Internet standardization process. Experienced network gurus may safely skip this chapter, and move on to the next chapter where you begin developing the tools needed to write your own network programs in Java. Networks A network is a collection of computers and other devices that can send data to and receive data from one another, more or less in real time. A network is often connected by wires, and the bits of data are turned into electromagnetic waves that move through the wires. However, wireless networks transmit data using radio waves; and most long- distance transmissions are now carried over fiber-optic cables that send light waves through glass filaments. There’s nothing sacred about any particular physical medium for the transmission of data. Theoretically, data could be transmitted by coal-powered computers that send smoke signals to one another. The response time (and environ‐ mental impact) of such a network would be rather poor. Each machine on a network is called a node. Most nodes are computers, but printers, routers, bridges, gateways, dumb terminals, and Coca-Cola™ machines can also be no‐ des. You might use Java to interface with a Coke machine, but otherwise you’ll mostly talk to other computers. Nodes that are fully functional computers are also called hosts. I will use the word node to refer to any device on the network, and the word host to refer to a node that is a general-purpose computer. Every network node has an address, a sequence of bytes that uniquely identifies it. You can think of this group of bytes as a number, but in general the number of bytes in an address or the ordering of those bytes (big endian or little endian) is not guaranteed to 2 | Chapter 1: Basic Network Concepts
  • 31.
    match any primitivenumeric data type in Java. The more bytes there are in each address, the more addresses there are available and the more devices that can be connected to the network simultaneously. Addresses are assigned differently on different kinds of networks. Ethernet addresses are attached to the physical Ethernet hardware. Manufacturers of Ethernet hardware use preassigned manufacturer codes to make sure there are no conflicts between the addresses in their hardware and the addresses of other manufacturers’ hardware. Each manufacturer is responsible for making sure it doesn’t ship two Ethernet cards with the same address. Internet addresses are normally assigned to a computer by the organi‐ zation that is responsible for it. However, the addresses that an organization is allowed to choose for its computers are assigned by the organization’s Internet service provider (ISP). ISPs get their IP addresses from one of four regional Internet registries (the reg‐ istry for North America is ARIN, the American Registry for Internet Numbers), which are in turn assigned IP addresses by the Internet Corporation for Assigned Names and Numbers (ICANN). On some kinds of networks, nodes also have text names that help human beings identify them such as “www.elharo.com” or “Beth Harold’s Computer.” At a set moment in time, aparticularnamenormallyreferstoexactlyoneaddress.However,namesarenotlocked to addresses. Names can change while addresses stay the same; likewise, addresses can change while the names stay the same. One address can have several names and one name can refer to several different addresses. All modern computer networks are packet-switched networks: data traveling on the network is broken into chunks called packets and each packet is handled separately. Each packet contains information about who sent it and where it’s going. The most importantadvantageofbreakingdataintoindividuallyaddressedpacketsisthatpackets from many ongoing exchanges can travel on one wire, which makes it much cheaper to build a network: many computers can share the same wire without interfering. (In contrast,whenyoumakealocaltelephonecallwithinthesameexchangeonatraditional phone line, you have essentially reserved a wire from your phone to the phone of the person you’re calling. When all the wires are in use, as sometimes happens during a major emergency or holiday, not everyone who picks up a phone will get a dial tone. If you stay on the line, you’ll eventually get a dial tone when a line becomes free. In some countries with worse phone service than the United States, it’s not uncommon to have to wait half an hour or more for a dial tone.) Another advantage of packets is that checksums can be used to detect whether a packet was damaged in transit. We’re still missing one important piece: some notion of what computers need to say to pass data back and forth. A protocol is a precise set of rules defining how computers communicate: the format of addresses, how data is split into packets, and so on. There are many different protocols defining different aspects of network communication. For example, the Hypertext Transfer Protocol (HTTP) defines how web browsers and Networks | 3
  • 32.
    servers communicate; atthe other end of the spectrum, the IEEE 802.3 standard defines a protocol for how bits are encoded as electrical signals on a particular type of wire. Open, published protocol standards allow software and equipment from different ven‐ dors to communicate with one another. A web server doesn’t care whether the client is a Unix workstation, an Android phone, or an iPad, because all clients speak the same HTTP protocol regardless of platform. The Layers of a Network Sending data across a network is a complex operation that must be carefully tuned to the physical characteristics of the network as well as the logical character of the data being sent. Software that sends data across a network must understand how to avoid collisions between packets, convert digital data to analog signals, detect and correct errors, route packets from one host to another, and more. The process is further com‐ plicated when the requirement to support multiple operating systems and heterogene‐ ous network cabling is added. To hide most of this complexity from the application developer and end user, the dif‐ ferent aspects of network communication are separated into multiple layers. Each layer represents a different level of abstraction between the physical hardware (i.e., the wires and electricity) and the information being transmitted. In theory, each layer only talks to the layers immediately above and immediately below it. Separating the network into layers lets you modify or even replace the software in one layer without affecting the others, as long as the interfaces between the layers stay the same. Figure 1-1 shows a stack of possible protocols that may exist in your network. While the middle layer protocols are fairly consistent across most of the Internet today, the top and the bottom vary a lot. Some hosts use Ethernet; some use WiFi; some use PPP; some use something else. Similarly, what’s on the top of the stack will depend completely on which programs a host is running. The key is that from the top of the stack, it doesn’t really matter what’s on the bottom and vice versa. The layer model decouples the ap‐ plication protocols (the main subject of this book) from the physics of the network hardware and the topology of the network connections. 4 | Chapter 1: Basic Network Concepts
  • 33.
    Figure 1-1. Protocolsin different layers of a network There are several different layer models, each organized to fit the needs of a particular kind of network. This book uses the standard TCP/IP four-layer model appropriate for the Internet, shown in Figure 1-2. In this model, applications like Firefox and Warcraft run in the application layer and talk only to the transport layer. The transport layer talks only to the application layer and the Internet layer. The Internet layer in turn talks only to the host-to-network layer and the transport layer, never directly to the application layer. The host-to-network layer moves the data across the wires, fiber-optic cables, or other medium to the host-to-network layer on the remote system, which then moves the data up the layers to the application on the remote system. Figure 1-2. The layers of a network For example, when a web browser sends a request to a web server to retrieve a page, the browser is actually talking to the transport layer on the local client machine. The trans‐ The Layers of a Network | 5
  • 34.
    port layer breaksthe request into TCP segments, adds some sequence numbers and checksumstothedata,andthenpassestherequesttothelocalinternetlayer.Theinternet layer fragments the segments into IP datagrams of the necessary size for the local net‐ work and passes them to the host-to-network layer for transmission onto the wire. The host-to-network layer encodes the digital data as analog signals appropriate for the particular physical medium and sends the request out the wire where it will be read by the host-to-network layer of the remote system to which it’s addressed. The host-to-network layer on the remote system decodes the analog signals into digital data, then passes the resulting IP datagrams to the server’s internet layer. The internet layer does some simple checks to see that the IP datagrams aren’t corrupt, reassembles them if they’ve been fragmented, and passes them to the server’s transport layer. The server’stransportlayercheckstoseethatallthedataarrivedandrequestsretransmission of any missing or corrupt pieces. (This request actually goes back down through the server’s internet layer, through the server’s host-to-network layer, and back to the client system, where it bubbles back up to the client’s transport layer, which retransmits the missing data back down through the layers. This is all transparent to the application layer.) Once the server’s transport layer has received enough contiguous, sequential datagrams, it reassembles them and writes them onto a stream read by the web server running in the server application layer. The server responds to the request and sends its response back down through the layers on the server system for transmission back across the Internet and delivery to the web client. As you can guess, the real process is much more elaborate. The host-to-network layer is by far the most complex, and a lot has been deliberately hidden. For example, it’s entirely possible that data sent across the Internet will pass through several routers and their layers before reaching its final destination. It may need to be converted from radio waves in the air to electrical signals in copper wire to light pulses in fiber-optic cables and back again, possibly more than once. However, 90% of the time your Java code will work in the application layer and only need to talk to the transport layer. The other 10% of the time, you’ll be in the transport layer and talking to the application layer or the internet layer. The complexity of the host-to-network layer is hidden from you; that’s the point of the layer model. 6 | Chapter 1: Basic Network Concepts
  • 35.
    Exploring the Varietyof Random Documents with Different Content
  • 36.
    FAITH i ssman has taken from me the form of his being and the manner of his speech. What to thee is evil, to another is good, to thee it is poison, to another it is sweet honey. To me words are nothing. I look into the heart of man." VII The Persian poet, Mohammed Roumi, who lived in the thirteenth century, is the author of the celebrated poem " Masnava." It contains some remarkable verses on prayer which are worthy of a trusting soul : — " A certain man cried out in the silence of the night, • Oh, Allah ! ' But Satan answered, ' Be silent, thou fool, thou hast babbled enough already ! Thou wilt never hear an answer from the height of the throne, however much thou mayst cry " Allah ! " and look disheartened.' " The man's heart was troubled, and he hung his head. Then appeared to him the prophet Kisr, and asked : ' Why hast thou ceased to call on God, and repented of thy prayers ? ' The man answered, ' I got no answer from Allah ; I heard no voice saying, " I am here," and I fear that the gates of salvation are shut against me.' Kisr answered, ' Thus has Allah commanded me, " Go thou to him and say, ' Oh, man, tried by much, have I not commanded thee to serve me ; have I not commanded thee to call on me. And my reply, " Here am I " is the same as thine " Oh, Allah ! " Thy suffering, thy ardour, and thy zeal, all these are my messengers to thee : when
  • 37.
    156 REFLECTIONS OFA RUSSIAN STATESMAN thou strugglest with thyself and cryest for help, by this struggle and cry I draw thee to myself, and answer thy prayer. Thy fear and thy love are the signs of my forgiveness, and in thy words, "O Allah ! " is a multitude of answers, " I am with thee." ' "
  • 38.
    THE IDEALS OFUNBELIEF The ancient words, " The fool hath said in his heart, there is no God," apply with especial force to- day. Their truth is plainer than the sun, although now all " progressive minds " are possessed by a passionate desire to live without God, to conceal Him, to deny His presence. Even men at heart benevolent and honourable ask themselves how they may realise benevolence, honour, and conscience without God. The Government of France, in the last stage of political disintegration, has organised its national schools without God. Among us, unhappily, certain representatives of intelligence have rivalled the Moscow princess, who said, " Ah, France, no better country in the world ! " — for not long ago a celebrated schoolmaster pointed out the French scholastic system as a model worthy of imitation. Among the latest books officially prescribed for study in the female schools of France is one entitled, " Instruction Morale et Civique des Jeunes Filles." This is in the nature of a secular catechism of morals, appointed to replace the study of the Word of God. This book is worthy of notice. It is divided into three sections, each bearing a different title. The first is composed of certain moral precepts on duty, honesty, conscience, and so forth. The second part iS7
  • 39.
    158 REFLECTIONS OFA RUSSIAN STATESMAN contains a short description of the State and of the national institutions. The third part treats of woman, her mission, faculties, and virtues. The matter in the book is concise, simple, and clear, written as a textbook ought to be with a multitude of clear examples and illustrations. No exception can be taken to the manner of this book ; it preaches order, good morals, purity of thought and intention, kind deeds ; it approves with emphasis the sentiment and recognition of duty, and carefully sets forth a woman's duties in social and domestic life. One thing alone is notable. On no single page is mentioned the name of God, nor is there the slightest reference to the religious feeling. The author, after explaining the great importance of the part played in man by conscience, defines it thus : " Conscience is our conception of the opinion which others ..have about us and our actions" {consideration de Vopinion des antres). On this treacherous and mutable base, the opinion of others, is affirmed the moral foundation of our lives. How excellently this illustrates the ancient proverb, " Who thinks himself too wise becomes a fool." Unhappily, to this stream of idiotcy flooding France to-day are drawn even from our poor Russia little rills of native intelligence ; and in our newspapers and gazettes, in our leading articles and feuilletons are repeated in chorus the words of the Moscow princess. To the same chorus too often are drawn those well-meaning, but simple and inexperienced men, who fancy newspapers must bring to them some " new word " of civilisation. Nothing is more deplorable than the reasoning on
  • 40.
    THE IDEALS OFUNBELIEF 159 the subject of education of our journalist critics, who tell us that while religion and religious training are indispensable, churches and ministers must be abolished. Sometimes they speak more plainly. " We do not reject religious teaching, we even demand it ; we cannot understand education without it ; but we object to Clericalism." By this term we must understand the Church and everything appertaining thereto. This Jesuitical casuistry, which the apostles of popular education have made peculiarly their own, misleads many readers who cannot appreciate subtlety in writing. These good men do not know that the word religion, as many other words, has changed its signification, and is made by many to imply something from which, if they but understood it, believers in God would recoil with abhorrence. They do not know that in our time religion may exist without God, and that the very word God, in its application by so-called men of science, has a double meaning. In 1882 appeared a remarkable book which awakened general interest. Therein the negation of God, by the enemies of all religion, was expressed with ferocity, with reckless and malicious irony, with a demand for the exclusive consideration of matter in the universe. The first part of the work expressed, in a tranquil tone, with dignity, with an ideal outlook on life, the whole teaching of the religion without God. This book was entitled "Natural Religion" (London, 1882). Its author, Professor Seeley of Oxford, was he whose former "Ecce Homo," which appeared ten years before, had attracted the attention, not only of men of
  • 41.
    160 REFLECTIONS OFA RUSSIAN STATESMAN science, but of religious idealists who sought in it some new word on Christ and the Christian faith. A Russian translation of this latter work has been published by an admirer. But to the adherents of the Church Mr Seeley's work seemed strange and questionable. Few could look on it without distrust. This book contained an artistic analysis of the earthly life and character of Jesus Christ, treating exclusively of his human nature. It was written in a spirit of deep piety, in the language of philosophy, with occasional recourse to the terminology of theologians. The object of the "work seemed to be to hold up the image of Christ to pious imitation. The author, it seemed, was a Christian, full of religious feeling. But many religious readers took alarm, as if their views and sentiments of Christianity were not in accord with the views and sentiments of the author. The picture of Christ was a picture of supreme holiness, purity, and goodness, but not that picture which we have been taught to venerate from childhood — not the Christ honoured by the Christian Church. Something discordant appeared throughout the book, as if the author had either lost all faith, or was on the point of losing it. Nevertheless, the writer plainly affirmed his faith in the existence of a personal God ; in the immortality of the human soul ; in the Messianic significance of the appearance of Christ ; and even, although with some hesitation, in the reality of His miracles. Ten years passed ; again Mr Seeley appeared as the inspired prophet of religion, this time a new religion, and not the religion of Christ. The ancient
  • 42.
    THE IDEALS OFUNBELIEF 161 revelation, he said, had done its work ; instead, a new revelation had come ; the naturalists, historians, and philologists of the age had borne us a revelation of which the ancient prophets had never dreamed. The Biblical criticism of German scholars was greater and more perfect than the Bible itself. With uncommon simplicity, turning to the believers and members of the Church, he asks : " Why should we quarrel, why should there be strife between us? We may unite in a single faith. We, men of science, also trust in God. Our God is Nature, which in one sense is a revelation too. Therefore we are not -atheists," he repeats, " and the battle between us, men of science, and you, men of faith, is merely a battle of words. Is it not the same ? For us God is Nature, and the scientific theory of the universe is a theory of theism also. Nature is a force existing outside of us ; its law for us is absolute : there is the divinity which we adore." Is it not strange that the author, while rejecting the personal existence of God, at the same time protests with energy against the accusation of atheism, which he rejects and condemns? What is atheism, then? This question Mr Seeley answers with a tortuous subtlety which to a simple mind must seem insanity. "There is an atheism which is a mere speculative crotchet, and there is an atheism which is a great moral disease. . . . The purest form of such real atheism might be called by the general name of wilfulness. All human activity is a transaction with Nature. It is the arrangement of a compromise between what we want on the one hand, and what Nature has decreed on the other. Not to recognise anything but your own will, to fancy anything within your reach if you only will strongly L
  • 43.
    162 REFLECTIONS OFA RUSSIAN STATESMAN enough, to acknowledge no superior power outside yourself which must be considered, and in some way propitiated, if you would succeed in any undertaking : this is complete wilfulness, or, in other words, pure atheism." — Seeley, " Natural Religion," p. 27. To illustrate this obscure and disorderly argument, our author takes as example a country in its fate a symbol of pure atheism, and points to Poland. " Sedet aternumque sedebit" says he, " that unhappy Poland, not indeed extinguished, but partitioned, and every thirty years decimated anew, expiates the crime of atheistic wilfulness, the fatal pleasure of unbounded individual liberty, which rose up against the very nature of things." — Ibid. p. 29. Having disclosed this theory of religion, he describes in detail how the religious feeling is born from science, and, passing through the prism of imagination, is refracted in the moral nature of man into a religious trinity : the religion of Nature, the religion of Humanity, and the religion of Beauty. In this book, written with talent and spirit, is a doctrine by no means new, although for the first time expressed with such completeness. The reader finds there the well-known features of the Positivism so fashionable in our time — features familiar through the writings of Kant, George Eliot, and Herbert Spencer — the well-beloved of Russian translators. Not one of these writers exposes so clearly the internal weakness of this fashionable theory as the author of " Natural Religion." To what idiotcy must the mind have sunken when, drawn by the pride of self-adoration, it rejects the supernatural in life and nature, and strives to build a theory of life in relation to the universe. This theory is condemned to turn in an
  • 44.
    THE IDEALS OFUNBELIEF 163 enchanted circle, and to contradict itself for ever. Denying a personal God, in vain it would sustain religion and establish an object of religious feeling; for, except the living God, there can be no object of religion. Rejecting the invisible world, the immortality of the soul, and the future life, it proclaims that the end of life is happiness, and would confine humanity within the limits of matter and of its earthly nature. Condemning revelation as invention or fantasy, and every dogma as falsehood, it seeks to support itself by a new dogma, proclaiming as an indisputable axiom the constant and endless progress of humanity. This theory, in a flash, reflects that wilfulness and that obduracy of thought which our author combines in his conception of atheism. It shows no sign of that clear and simple confidence which serves as a symptom of the truth and durability of doctrines. In their sermons on the happiness of humanity, its prophets all stumble on an actuality which they cannot deny. This actuality is the inevitable presence of evil and of evil works, of violence and of injustice in human life — the argument of pessimism. This argument cannot be lived down, although some of the apostles of Positivism strive to stifle its voice or hypocritically to ignore it, while others, more conscientious, stand by it with grief and questioning. To the number of the last belongs our author. While extolling the new religion of Nature, Humanity, and Beauty, and proving the strength and actuality of the cult it preaches, at the same time he admits that hardly have we found satisfaction in these ideas when pessimism raises its head
  • 45.
    164 REFLECTIONS OFA RUSSIAN STATESMAN and brings us to despair. If it were not for pessimism, he declares, nothing would destroy our religious beliefs. And at the end of the book, when crowning his edifice, he makes these remarks : "The more our thoughts widen and deepen, as the universe grows upon us and we become accustomed to boundless space and time, the more petrifying is the contrast of our own insignificance, the more contemptible become the pettiness, shortness, fragility of the individual life. A moral paralysis creeps upon us. For a while we comfort ourselves with the notion of self-sacrifice ; we say, What matter if I pass, let me think of others ! But the other has become contemptible no less than the self; all human griefs alike seem little worth assuaging, human happiness too paltry at the best to be worth increasing. The whole moral world is reduced to a point ; the spiritual city, 'the goal of all the saints/ dwindles to the 'least of little stars'; good and evil, right and wrong, become infinitesimal, ephemeral matters, while eternity and infinity remain attributes of that only which is outside the realm of morality. Life becomes more intolerable the more we know and discover, so long as everything widens and deepens, except our own duration, and that remains as pitiful as ever. The affections die away in a world where everything great and enduring is cold ; they die of their own conscious feebleness and bloodlessness. "Supernatural Religion met this want by connecting Love and Righteousness with eternity. If it is shaken, how shall its place be supplied ? And what would Natural Religion avail then ? " Ibid. p. 261. Who would believe that these words were written by the ardent prophet of Natural Religion? Thus may a serious mind be entangled in the intellectual network it weaves. The essence of this work, with all its moderation of tone, with all the sincerity of its author, is a joyless paradox. That the various systems of cosmology, the scientific, the artistic, and the humanist, contain elements of religious feeling cannot be denied.
  • 46.
    THE IDEALS OFUNBELIEF 165 But they do not embody the elements of a new faith, of a new church ; they are separate limbs — disjecta membra — of the Christian philosophy of life. Religion is impossible without the recognition of axiomatic truths unattainable by the path of induction. To such truths belong the existence of a personal God, and the immaterial nature of the human soul, whence springs supernaturalism, without which religion is inconceivable. With the exception of mathematics, scientific truths are by their nature hypothetical : they exist consciously only for scholars, and only by deception may be imparted to the mass in dogmatic form. This deception obtains among us and progresses — of this we find fresh evidence every day. II Intolerance of strange beliefs and strange opinions has never been so sharply expressed as it is nowadays by the apostles of radical and negative beliefs, among whom such intolerance is merciless and bitter, and joined with animosity and contempt. When we consider the relations of these teachers to the new doctrines they proclaim, their intolerance is more abhorrent than the old religious intolerance which expressed itself in sanguinary persecution. Then persecution was based on unqualified faith in a truth which absolutely existed. When men believe that they possess an absolute truth, sprung from the ultimate principle of life and involving happiness for all, as the Moslem believes in the Koran, it is conceivable that they may consider it a duty r
  • 47.
    166 REFLECTIONS OFA RUSSIAN STATESMAN not only openly to preach their doctrine, but, if need be, by violence to enforce it upon others. But when it is merely an opinion, although it may be that nothing is more probable for him who formed it, how can we understand fanaticism so great that its advocate does not admit not only contradiction but even compromise, although conditional and temporary, with adverse opinion? Yet such passionate attachment to their own convictions or to the doctrines of their schools is an attribute to all the prophets of negation. Rejecting, as if it were not, the whole former history of the spiritual development of humanity, ignoring all ancient faiths and the spiritual conditions of peoples, denying all rights of independent existence, repelled not by the sanctity of personal faith, they claim admittance to every soul, and everywhere strive to establish their new religion. This they call the truth of their convictions. One of the representatives of the doctrine of Comte and the Positivists (John Morley "On Compromise") maintains that the first duty of every man to himself and to humanity is to solve in his heart the question, Does he or does he not believe in the existence of God ? Should he reach the conviction that faith in God is no better than a blind and unhealthy superstition, it is his sacred duty to break in with this conviction on every soul, to take advantage of every occasion to convert, firstly,his kinsmen and neighbours, and then, if possible, the people ; to proclaim it everywhere, and in private and public life wholly to renounce all forms and ceremonies which, directly or indirectly, express a faith opposed to his conviction. What is this but a terrible violence against the conscience of
  • 48.
    THE IDEALS OFUNBELIEF 167 others — and in the name of what? In the name of a personal opinion. In this hell of vanity we can find neither love nor faith. But without love and without faith there can be no truth. How different to listen to the voice of the old true teacher ! What faith and love, what knowledge of the human soul is there in those words in which the Apostle to the Corinthians enjoins respect for human conscience. He knows the truth, but with his deep spiritual knowledge how cautiously would he approach the human soul ! His purpose is that the soul shall accept and embrace the new belief in the spirit of sincerity and truth by faith alone, without disunion, without discord with itself. All that comes not from faith is sin. And the Apostle teaches the strong and learned that they must spare the consciences of their weaker brethren even in superstition, when the soul is not ripe to accept the truth with entire faith. The Apostle, the herald of Christian freedom, acting from conviction, sacrifices freedom itself to the sanctity of conscience, knowing that conscience is dearer than all. You know, says he, that meat commendeth us not to God ; for neither if we eat are we the better ; neither if we eat not are we the worse. You know that the idol is nothing, that the false God does not exist, therefore with quiet conscience buy meat and eat it, which was brought as sacrifice to the idol. Ill Nothing is more surprising than the fatuity of clever men who have grown up in estrangement from
  • 49.
    168 REFLECTIONS OFA RUSSIAN STATESMAN actual life, and who are blinded by confidence in the infallibility of logic. By adoration of reason they are seduced from religion, and at last incited to hatred of every faith in the only living God. But those who at the same time are men of conscience, find that they cannot rid themselves of the aspiration to faith innate in humanity ; those whose hearts are unhardened by the severity of logic admit the lawfulness of religious feeling in man, and strive to satisfy it by some religion devised by themselves. We may wonder at the fancifulness of plans contrived by minds apparently striving to drive away everything like fancy out of their reasoning and deliberations. Strauss, in his work on "The Old and the New Faith," while rejecting Christianity, speaks with enthusiasm of the religious sentiment, but as its object and centre replaces the living God with the idea of the World, the so-called Universum. After the death of Mill, his occasional thoughts on religion appeared in London under the title, " Three Essays on Religion : Nature, the Utility of Religion, and Theism." The utility of religion he admits without reserve, and, while rejecting Christianity, he speaks of the individual Christ with the greatest enthusiasm. "The value of religion to the individual, both in the past and present, as a source of personal satisfaction and of elevated feelings, is not to be disputed. But it has still to be considered whether, in order to obtain this good, it is necessary to travel beyond the boundaries of the world which we inhabit j or whether the idealisation of our earthly life, the cultivation of a high conception of what it may be made, is not capable of supplying a poetry, and, in the best sense of the word, a religion, equally fitted to exalt the feelings, and (with the same aid from education) still better calcu 
  • 50.
    THE IDEALS OFUNBELIEF 169 lated to ennoble the conduct, than any belief respecting the unseen powers." "Three Essays on Religion" (Utility of Religion), pp. 104-5. London, 1874. The question is worthy of Mill as we know him by the history of his education. It is interesting to note how in his decision of this question, Mill could not, with Strauss, accept as decisive the idea of the Universe, for Mill, strange to say, did not trust in Nature. In the beginning of the same book, true as ever to his estrangement from reality, he speaks of " Enquiry into the truth of the doctrines which make Nature a test of right and wrong, good and evil, or which in any mode or degree attach merit or approval to following, imitating, or obeying Nature." — Ibid. (Nature), p. 13. These doctrines Mill rejects, for in Nature he sees blind force and nothing more. Nature inspires desires which it does not satisfy ; it builds great edifices, powers, and actions, in a moment to overthrow them ; it destroys blindly and indiscriminately all that it has created. For this reason Mill declines to construct on Nature any system of morals or of religion. What, then, does he think ? These are his own words : "When we consider how ardent a sentiment, in favourable circumstances of education, the love of country has become, we cannot judge it impossible that the love of that larger country, the world, may be nursed into similar strength, both as a source of elevated emotion and as a principle of duty. He who needs any other lesson on this subject than the whole course of ancient history affords, let him read Cicero De Officiis. It cannot be said that the standard of morals laid down in that celebrated treatise is a high standard. To our notions, it is on many points unduly lax, and admits capitu 
  • 51.
    170 REFLECTIONS OFA RUSSIAN STATESMAN lations of conscience. But on the subject of duty to our country there is no compromise. That any man, with the smallest pretensions to virtue, could hesitate to sacrifice life, reputation, family, everything valuable to him, to the love of country, is a supposition which this eminent interpreter of Greek and Roman morality cannot entertain for a moment. If, then, persons could be trained, as we see they were, not only to believe in theory that the good of their country was an object to which all others ought to yield, but to feel this practically as the grand duty of life, so also may they be made to feel the same absolute obligation towards the universal good. A morality grounded on large and wise views of the whole, neither sacrificing the individual to the aggregate nor the aggregate to the individual, but giving to duty, on the one hand, and to freedom and spontaneity, on the other, their proper province, would derive its power in the superior natures from sympathy and benevolence and the passion for ideal excellence ; in the inferior, from the same feelings cultivated up to the measure of their capacity, with the superadded force of shame. This exalted morality would not depend for its ascendency on any hope of reward ; but the reward which might be looked for, and the thought of which would be a consolation in suffering, and a support in moments of weakness, would not be a problematical future existence, but the approbation in this of those whom we respect, and ideally of all those, dead or living, whom we admire or venerate. For, the thought that our dead parents or friends would have approved our conduct is a scarcely less powerful motive than the knowledge that our living ones do approve it ; and the idea that Socrates, or Howard or Washington, or Antoninus, or Christ, would have sympathised with us, or that we are attempting to do our part in the spirit in which they did theirs, has operated on the very best minds as a strong incentive to act up to their highest feelings and convictions. "To call these sentiments by the name of morality, exclusively of any other title, is claiming too little for them. They are a real religion 5 of which, as of other religions, outward good works (the utmost meaning usually suggested by the word morality) are
  • 52.
    only a part,and are indeed rather the fruits of the religion than the religion itself. The essence of religion is the strong and earnest direction of the emotions and desires towards an ideal object, recognised as of the highest excellence, and as rightfully paramount
  • 53.
    THE IDEALS OFUNBELIEF 171 over all selfish objects of desire. This condition is fulfilled by the Religion of Humanity in an eminent degree, and in as high a sense, as by the supernatural religions even in their best manifestations, and far more so than in any of their others." Ibid. (Utility of Religion), pp. 107-9. The foregoing words explain themselves. They show the narrowness, we should say rather the idiotcy, of human wisdom when it seeks an abstract conception of life and of humanity, while ignoring life itself, and rejecting the human soul. Such a religion may indeed be sufficient for thinkers like Mill, secluded from the world in abstract speculation, but how shall the people accept and understand it ? — the people, a living organism held in communion only by living sentiment and conscience, and repelled by abstractions and generalities. In the people, such a religion, if it bore fruit at all, would bear fruit in reversion to paganism. The people — which we cannot conceive detached from Nature — if it forgot the faith of its fathers, would again personify the idea, either of the universe, resolving it into separate forces, or of that humanity which stands as a binding spiritual principle, resolving it also into its representative spiritual forces ; and there would result so many false gods instead of one true God. It cannot be that we are condemned to suffer this?
  • 54.
    THE NEW RELIGIONAND THE NEW MARRIAGE We are told that our religion is drawing to its end, that a new faith will replace it, the dawn of which is on the point of appearing. God grant that this maybe delayed, and that, if it must come, it may not be for long ! For it will not be a time of enlightenment, but of darkness. The ancient faith contains all that human nature has of sincerity — the sincerity of direct sensations and conscience, the sincerity which, from the depths of our spiritual nature, corresponds to the words of divine revelation. This is a living truth, and its roots are sunken in the souls of all. Of it was it said : " Every one that is of the truth heareth my voice." The ancient faith was founded on the consciousness of every man of a living soul which is immortal and one, a living soul he confounds neither with Nature nor with humanity. By this ' he knows himself before God and before his fellow-men, by this he wishes to live eternally. By this he enters into the free alliance of love with others, and, as he lives in his soul, so he answers for it himself. Through this the existence of his Creator is revealed as simply as his own life, and by this simple feeling, independently of reason, he maintains his faith. The prophets of a new religion appear. Some laugh at the ancient faith, and would destroy it, 172
  • 55.
    THE NEW RELIGIONAND THE NEW MARRIAGE 173 without the will to create anew. Others appear more serious ; they seek supreme wisdom, and strive to impose on us a wisdom of their own. Each offers us his own conception of truth, his favourite system of religion, for all apprehend the necessity of religion, and each would create one himself. How pitiable are these creations I They lack the power to draw the living soul and inspire it with a living idea, for not one of them sets the living spirit of God in the centre of his faith. In recent times many various systems have appeared from the pens of philosophers, each at will attempting to construct for humanity a faith without God. Each would constitute his system on the basis of reason, by its nature an absurdity. For human reason in a straight path, ignoring and rejecting no facts of Nature or of the human soul, can never eliminate the idea of God. The true source of atheism is not in the mind but in the heart, for, as the prophet said, "The fool hath said in his heart, there is no God." In the heart, that is, in the will, is the source of all error, however reason may seek to explain it. Error is born by the desire of the heart for full freedom, by rebellion against the commandments, and against Him who is the beginning and the end of all commandments. To free oneself of the commandments, there is no other path than to reject their supreme authority, and to replace it by the authority of self. The oldest of human histories is repeated from generation to generation, " Ye shall be as gods, knowing good and evil." This has been the source of atheism from immemorial time. It is wonderful, indeed, how reason deceives itself.
  • 56.
    174 REFLECTIONS OFA RUSSIAN STATESMAN Without God it seems that there can be no religion, yet such a religion is proclaimed by atheists. They say, " In the place of these outworn tales of God let us put the truth. God is nowhere visible, while Nature and humanity are actual facts. Humanity is not only a fact, it is a force able, by the paths of reason and experience, to attain in the course of centuries unimaginable perfection. This idea of progression contains such internal force and profundity that it is enough to compensate man for religious sentiment, and to bind the race in the universal religion of humanity." Is this not the Biblical, " Ye shall be as gods " ? Such are the doctrines of modern Positivist science, and of the so-called Utilitarianism. From another side appears the celebrated apostle of the Tubingen school, the pillar of Biblical criticism, who lived to an old age in denial of the historic foundation of Christianity. This is Dr Strauss, the author of the " Life of Jesus " ; the author of " The Old and the New Religion," in which he himself says he has made his confession, and given to the world the result of all his learned labours and philosophical speculations on God, on Nature, and on humanity. In youth, in the " Life of Jesus," he undertook, with some respect and caution, the analysis of those facts consecrated by the traditional belief of man, touching with tenderness the fundamental ideas of faith. In this work is seen a remnant of respect for God. But later we find a furious irritation against the Godhead, as a false and pernicious fable which has corrupted the minds of mankind. But while rejecting God, by a strange incon 
  • 57.
    THE NEW RELIGIONAND THE NEW MARRIAGE 175 sistency of thought, he does not abandon the religious feeling. In himself he feels the necessity, and affirms the existence, of religious devotion. What is the object of this devotion, which at the same time has power to possess and inspire the soul ? Not a personal divinity which exists not, but the world {Uftiversum) which constitutes the source of all good and power — which exists by the law of pure reason. We demand, he says, for this Universe the same devout feeling as a good man of the ancient faith cherished towards God. What is this Universe, and what its spiritual element? Answering that question, Strauss reveals himself as a disciple of the Positivist philosophy, and of the new materialism. The doctrine of Kant and of Laplace on the exclusive activity of mechanical forces in the planetary system, he applies absolutely to all the phenomena of animal and spiritual life ; he regards the soul of man as nothing better than the result of the complex interaction of mechanical forces. The soul as a spiritual essence Strauss rejects. As might be expected, he accepts triumphantly the theories of Darwin on the Origin of Species, limiting not their application to the phenomena of the external world, but extending them capriciously to all the manifestations of life. The imperfection and inconsistency of Darwin's reasonings do not alarm him in the least. All doubt is eliminated by his new religion, by faith in his own hypothesis, incompatible, he tells us, with the existence of God. It matters not that such abstract hypotheses as spontaneous generation remain unproven. He cannot say how or when, but without doubt some day they
  • 58.
    REFLEC70NS OF ARUSSIAN STATESMAN will be prove. In considering the origin of man, he does not rouble to explain and reconcile the origin of his intellectual powers, his moral ideas, and his aesthcic conceptions. All is explained by the magic wois, "Natural Selection." Surely, if this capricious inituation with theory constitutes the new religion, hat religion is nothing better than a new superstitm. The doctrie of Darwin could not have appeal at a time mre opport new religion. It enlighu it gave ther. the keystc crown the valt of their his teaching with eagerne that the anent faith wa annihilated. From every apply his pnciples to all life, deducin conclusions Darwin neve dreamed, pupils out-cstanced the ma near when tey will condemn Meantime, te doctrines of application ■> the facts from hardly justif those apprehensio the faith wich they awakened herents. Th system of Galile Newton, all ew discoveries in ge their day aakei more agitati the faith ofl in no will it be " these are nt re and the firsfcnthusic to wane. Tey are ac the prophets of with a new 1 they sougl They seized then proc :rthrohast lena it /
  • 61.
    Welcome to ourwebsite – the ideal destination for book lovers and knowledge seekers. With a mission to inspire endlessly, we offer a vast collection of books, ranging from classic literary works to specialized publications, self-development books, and children's literature. Each book is a new journey of discovery, expanding knowledge and enriching the soul of the reade Our website is not just a platform for buying books, but a bridge connecting readers to the timeless values of culture and wisdom. With an elegant, user-friendly interface and an intelligent search system, we are committed to providing a quick and convenient shopping experience. Additionally, our special promotions and home delivery services ensure that you save time and fully enjoy the joy of reading. Let us accompany you on the journey of exploring knowledge and personal growth! ebookname.com