Learning Network Programming with Java Harness the hidden power of Java to build network-enabled applications with lower network traffic and faster processes Richard M Reese BIRMINGHAM - MUMBAI Learning Network Programming with Java Copyright © 2015 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book. Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information. First published: December 2015 Production reference: 1141215 Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK. ISBN 978-1-78588-547-1 www.packtpub.com Credits Author Project Coordinator Richard M Reese Shipra Chawhan Reviewer Proofreader Daniel MÜHLBACHLER Safis Editing Commissioning Editor Indexer Veena Pagare Monica Ajmera Mehta Acquisition Editors Production Coordinator Vivek Anantharaman Nilesh Mohite Rahul Nair Cover Work Nilesh Mohite Content Development Editor Arshiya Ayaz Umer Technical Editor Humera Shaikh Copy Editor Priyanka Ravi About the Author Richard M Reese has worked in both industry and academia. For 17 years, he worked in the telephone and aerospace industries, serving in several capacities, including research and development, software development, supervision, and training. He currently teaches at Tarleton State University, where he has the opportunity to apply his years of industry experience to enhance his teaching. Richard has written several Java books and a C Pointer book. He uses a concise and easy-to-follow approach to topics at hand. His Java books have addressed EJB 3.1, updates to Java 7 and 8, certification, functional programming, jMonkeyEngine, and natural language processing. I would like to thank my daughter, Jennifer, for her numerous reviews and contributions; my wife, Karla, for her continued support; and to the staff of Packt for their work in making this a better book. About the Reviewer Daniel MÜHLBACHLER got interested in computer science shortly after entering high school, where he later developed web applications as part of a scholarship system for outstanding pupils. He has a profound knowledge of web development (PHP, HTML, CSS/LESS, and AngularJS), and has worked with a variety of other programming languages and systems, such as Java/Groovy, Grails, Objective-C and Swift, Matlab, C (with Cilk), Node.js, and Linux servers. Furthermore, he works with some database management systems based on SQL, and also some NoSQL systems, such as MongoDB, and SOLR. This is also reflected in several projects that he is currently involved in at Catalysts GmbH. After studying abroad as an exchange student in the United Kingdom, he completed his bachelor's degree at Johannes Kepler University in Linz, Austria, with a thesis on aerosol satellite data processing for mobile visualization. This is where he also became familiar with processing large amounts of data. Daniel enjoys solving challenging problems and is always keen on working with new technologies, especially related to the fields of big data, functional programming, optimization, and NoSQL databases. More detailed information about his experience, as well as his contact details, can be found at www.muehlbachler.org and www.linkedin.com/in/danielmuehlbachler. www.PacktPub.com Support files, eBooks, discount offers, and more For support files and downloads related to your book, please visit www.PacktPub.com. Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub. com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details. At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks. TM https://www2.packtpub.com/books/subscription/packtlib Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books. Why subscribe? • Fully searchable across every book published by Packt • Copy and paste, print, and bookmark content • On demand and accessible via a web browser Free access for Packt account holders If you have an account with Packt at www.PacktPub.com, you can use this to access PacktLib today and view 9 entirely free books. Simply use your login credentials for immediate access. Table of Contents Preface vii Chapter 1: Getting Started with Network Programming 1 Network addressing using the InetAddress class 3 NIO support 5 Using the URLConnection class 5 Using the URLConnection class with buffers and channels 6 The client/server architecture 7 Creating a simple echo server 8 Creating a simple echo client 10 Using Java 8 to support the echo server and client 12 UDP and multicasting 14 Creating a multicast server 14 Creating the multicast client 15 Scalability 17 Creating a threaded server 17 Using the threaded server 19 Security 21 Creating a SSL server 21 Creating an SSL client 22 Generating secure keys 23 Summary 25 Chapter 2: Network Addressing 27 Networking basics 27 Understanding network basics 29 Network architectures and protocols 30 Using the NetworkInterface class 32 Getting a MAC address 35 Getting a specific MAC address 35 [ i ] Table of Contents Getting multiple MAC addresses 36 Network addressing concepts 37 URL/URI/URN 37 Using the URI class 39 Creating URI instances 39 Splitting apart a URI 40 Using the URL class 41 Creating URL instances 42 Splitting apart a URL 42 IP addresses and the InetAddress class 45 Obtaining information about an address 45 Address scoping issues 47 Testing reachability 48 Introducing the Inet4Address 49 Private addresses in IPv4 50 IPv4 address types 50 The Inet4Address class 51 Special IPv4 addresses 51 Introducing the Inet6Address class 52 Private addresses in IPv6 52 The Inet6Address class 53 Special IPv6 addresses 53 Testing for the IP address type 53 Using IPv4-compatible IPv6 addresses 54 Controlling network properties 56 Summary 56 Chapter 3: NIO Support for Networking 57 Java NIO 57 Introduction to buffers 59 Using channels with a time server 60 Creating a time server 61 Creating a time client 62 The chat server/client applications 63 The chat server 64 The chat client 66 Server/client interaction 67 The HelperMethods class 68 Handling variable length messages 69 Running the chat server/client application 71 Handling multiple clients 72 The parts server 72 The parts client handler 74 The parts client 75 [ ii ] Table of Contents Running the parts client/server 76 Asynchronous socket channels 78 Creating the asynchronous server socket channel server 79 Creating the asynchronous socket channel client 81 Other buffer operations 83 Bulk data transfer 83 Using a view 85 Using read-only buffers 86 Controlling socket options 86 Summary 87 Chapter 4: Client/Server Development 89 The HTTP protocol structure 89 The nature of HTTP messages 91 Initial request line format 92 Header lines 94 Message body 94 Client/Server interaction example 95 Java socket support for HTTP client/server applications 95 Building a simple HTTP server 96 Building a simple HTTP client 100 Client/server development using standard Java classes 102 Using the HttpURLConnection class 102 URL encoding 105 Using the HTTPServer class 106 Implementing a simple HTTPServer class 108 Managing response headers 112 Open source Java HTTP servers 113 Server configuration 115 Handling cookies 116 Summary 117 Chapter 5: Peer-to-Peer Networks 119 P2P functions/characteristics 120 Applications-based P2P networks 122 Java support for P2P applications 123 Distributed hash tables 123 DHT components 124 DHT implementations 126 Using JDHT 126 Using FreePastry 128 The FreePastry demonstration 129 Understanding the FreePastryExample class 129 [ iii ]