Blakes 21 Days Chapter 17 Document


Day 17, Communicating Across the Internet

Networking in Java

Opening a Stream Over the Net

First Program - Listing 17.1

Listing 17.1 - The Full Text of WebReader.java

The Explanation

Figure 17.1 - Running the WebReader application. - goes here

516

Blake's Figure - "Safari Can't Connect to the Server" message displayed in the browser.

520

Sockets

Second Program - Listing 17.2

Listing 17.2 - The Full Text of Finger.java

An Explanation

Figure 17.2 - Making a Finger request using a socket. - goes here

524

Socket Servers

Designing a Server Application

Third Program - Listing 17.3

LISTING 17.3 The Full Text of TimeServer.java

The Explanation

Testing the Server

Figure 17.3 - Launching an Internet server in a ServerSocket. - goes here

528

Figure 17.4 - Making a telnet connection to your TimeServer. - goes here

530

The java.nio Package

Buffers

Byte Buffers

Character Sets

Channels

Fourth Program - Listing 17.4

LISTING 17.4 The Full Text of BufferConverter.java

The Explanation

Figure 17.5 - Reading character data from a buffer. - goes here

534

Network Channels

Nonblocking Socket Clients and Servers

Fifth Program - Listing 17.5

LISTING 17.5 The Full Text of FingerServer.java

package com.java21days;

import java.io.*;
import java.net.*;
import java.nio.channels.*;
import java.util.*;

public class FingerServer {

    public FingerServer() {
        try {
            // Create a non-blocking server socket channel
            ServerSocketChannel sock = ServerSocketChannel.open();
            sock.configureBlocking(false);

            // Set the host and port to monitor
            InetSocketAddress server = new InetSocketAddress(
                "localhost", 79);
            ServerSocket socket = sock.socket();
            socket.bind(server);

            // Create the selector and register it on the channel
            Selector selector = Selector.open();
            sock.register(selector, SelectionKey.OP_ACCEPT);

            // Loop forever, looking for client connections
            while (true) {
                // Wait for a connection
                selector.select();

                // Get list of selection keys with pending events
                Set keys = selector.selectedKeys();
                Iterator it = keys.iterator();

                // Handle each key
                while (it.hasNext()) {

                    // Get the key and remove it from the iteration
                    SelectionKey sKey = (SelectionKey) it.next();

                    it.remove();
                    if (sKey.isAcceptable()) {

                        // Create a socket connection with client
                        ServerSocketChannel selChannel =
                            (ServerSocketChannel) sKey.channel();
                        ServerSocket sSock = selChannel.socket();
                        Socket connection = sSock.accept();

                        // Handle the Finger request
                        handleRequest(connection);
                        connection.close();
                    }
                }
             }
         } catch (IOException ioe) {
             System.out.println(ioe.getMessage());
         }
     }

    private void handleRequest(Socket connection)
        throws IOException {

        // Set up input and output
        InputStreamReader isr = new InputStreamReader (
            connection.getInputStream());
        BufferedReader is = new BufferedReader(isr);
        PrintWriter pw = new PrintWriter(new
            BufferedOutputStream(connection.getOutputStream()),
            false);

        // Output server greeting
        pw.println("Nio Finger Server");
        pw.flush();

        // Handle user input
        String outLine = null;
        String inLine = is.readLine();

        if (inLine.length() > 0) {
            outLine = inLine;
        }
        readPlan(outLine, pw);

        // Clean up
        pw.flush();
        pw.close();
        is.close();
    }

    private void readPlan(String userName, PrintWriter pw) {
        try {
            FileReader file = new FileReader(userName + ".plan");
            BufferedReader buff = new BufferedReader(file);
            boolean eof = false;

            pw.println("\nUser name: " + userName + "\n");

            while (!eof) {
                String line = buff.readLine();

                if (line == null) {
                    eof = true;
                } else {
                   pw.println(line);
                }
            }

            buff.close();
        } catch (IOException e) {
            pw.println("User " + userName + " not found.");
        }
    }

    public static void main(String[] arguments) {
        FingerServer nio = new FingerServer();
    }
}

The Explanation

FIGURE 17.6 - Making a Finger request from your Finger server. - goes here

538

Summary

Q & A

Quiz - Questions

  1. Which of the following is not an advantage of the new java.nio package and its related packages ?
    1. Large amounts of data can be manipulated quickly with buffers.
    2. Networking connections can be nonblocking for more reliable use in your applications.
    3. Streams are no longer necessary to read and write data over a network.
  2. In the Finger protocol, which program makes a request for information about a user ?
    1. The client
    2. The server
    3. Both can make that request.
  3. Which method is preferred for loading the data from a web page into your Java application ?
    1. Creating a Socket and an input stream from that socket
    2. Creating a URL and an HttpURLConnection from that object
    3. Loading the page using the method toString()

Answers

  1. C. The java.nio classes work in conjunction with streams. They don't replace them.
  2. A. The client requests information, and the server sends back something in response.
  3. B. Sockets are good for low-level connections, such as when you are implementing a new protocol.

Certification Practice

  1. What will be the output when this application is run ?
    1. First int: 78
    2. First int: 71
    3. First int: 70
    4. None of the above

Exercise