Book Image

Learning Network Programming with Java

Book Image

Learning Network Programming with Java

Overview of this book

Network-aware applications are becoming more prevalent and play an ever-increasing role in the world today. Connecting and using an Internet-based service is a frequent requirement for many applications. Java provides numerous classes that have evolved over the years to meet evolving network needs. These range from low-level socket and IP-based approaches to those encapsulated in software services. This book explores how Java supports networks, starting with the basics and then advancing to more complex topics. An overview of each relevant network technology is presented followed by detailed examples of how to use Java to support these technologies. We start with the basics of networking and then explore how Java supports the development of client/server and peer-to-peer applications. The NIO packages are examined as well as multitasking and how network applications can address practical issues such as security. A discussion on networking concepts will put many network issues into perspective and let you focus on the appropriate technology for the problem at hand. The examples used will provide a good starting point to develop similar capabilities for many of your network needs
Table of Contents (16 chapters)
Learning Network Programming with Java
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
Index

Using channels with a time server


The time server and client that were introduced in Chapter 1, Getting Started with Network Programming, will be implemented here to demonstrate the use of buffers and channels. These applications are simple, but they illustrate how buffers and channels can be used together. We will start by creating a server and then create a client that uses the server.

Creating a time server

The following code is the initial declaration of the ServerSocketChannelTimeServer class, which will be our time server. The ServerSocketChannel class's open method creates a ServerSocketChannel instance. The socket method retrieves the ServerSocket instance for the channel. The bind method then associates this server socket with port 5000. While the ServerSocketChannel class has a close method, it is easier to use the try-with-resources block:

public class ServerSocketChannelTimeServer {
    public static void main(String[] args) {
        System.out.println("Time Server started");
...