HTML Markup | JavaScript | Java | Computer Sci | Home & Links

Tutorial 17 - Java Networking

Network access is crucial to computer operations in the twenty first century. Java provides many built-in networking class objects through its .net, .nio and .rmi packages. java.net provides http connections and streams as well as protocol sockets. java.nio, java.nio.charset and java.nio.channels provide buffers, character sets and channels for multiplexed non-blocking applications that are more tolerant of dropped connections and time delays. java.rmi provides methods for remote method invocation. Some of these objects will be described in the following material.

Networking Basics

Internet addresses uniquely identify each computer on the network. They use a 4 byte dot IP notation such as 220.210.34.7 Domain Name Service allows us to use an easier to remember naming scheme. DNS servers translate the domain name such as amazon.com into its dot IP address.

Servers are any computer with resources (such as printers and disks) to be shared. Clients are entities that want to use these resources. Servers listen to their socket ports waiting for a client to connect with a service request. Servers are multithreaded to permit multiple services and multiple connects to the same service simultaneously. Proxy servers speak the client side of the protocol to another server. It acts as an agent of the client and can be set up to filter or cache data for it.

A network socket is a standard interface that uses the TCP/IP protocol to interconnect with a network. Sockets use IP address extensions or ports to connect to specific services such as FTP and telnet. Each port number (below 1024) has a reserved use. You can use Sockets.com or google Well-Known Port Numbers to find the port number for a service.

Internet Streams

Internet streams allow you to access remote document data. The java.net package provides several objects for networking at the stream level:

GetFile.java (found in jp7net.zip) demonstrates how to create a utility that displays both the header and the contents of an internet document. Seven main steps are involved:

  1. Create an URL object that represents the resource's WWW address.
  2. Create a HttpURLConnection object that opens a connection for the URL.
  3. Use the getContent() method to create an InputStreamReader.
  4. Use the InputStreamReader to create a BufferedReader object.
  5. Use the getHeaderFieldKey(idx) and getHeaderField(idx) methods to retrieve header information.
  6. Read the contents from the BufferedReader stream.
  7. Write the contents to a Swing GUI textbox.

Warning: Both the access and display methods do not work for media files! If you are fetching image or audio files, use the technique from the packager project.

Project: filecopy()

The fileCopy() method uses the java.nio package FileChannel class to efficiently stream one file to another using non-blocking channels.

  public void fileCopy(String src,String dst) //uses java.nio.channels.*
  {
	try {
        FileChannel srcChannel = new FileInputStream(src).getChannel();
        FileChannel dstChannel = new FileOutputStream(dst).getChannel();
        dstChannel.transferFrom(srcChannel, 0, srcChannel.size());
        srcChannel.close(); dstChannel.close();
    } catch (IOException e) {;}
  }

Project: fileGrab

fileGrab.java uses a stream connection to a remote website and a whitelist (aka packing list) to download selected files (including those in subfolders). The files are then stored in the user's current folder (and subfolders). This utility is useful for fetching subsections of a website such as a group of tutorials.

Socket Programming

TCP/IP sockets can be used to access protocols other than http. The java.net package provides several objects for networking at the TCP/IP socket level:

The following programs duplicate existing client utilities but demonstrate how to write TCP/IP applications.

Whois.java (found in jp7net.zip) accesses a directory service that provides information about a specific host. It makes a socket connection to internic.net (the registrar for commercial sites), sets a timeout and establishes a stream to access the data. Once compiled, test Whois with java Whois amazon.com.

Finger.java (found in jp7net.zip) accesses a directory service that provides information about a particular user based on his .plan and .project files. It makes a socket connection, sets a timeout and establishes a stream to access the data. Unfortunately most hosts have removed their finger software because of address harvesting. One remaining site for testing is hlr@well.com (aka hwl@well.sf.ca.us).

TimeServer.java (found in jp7net.zip) is a ServerSocket application that places the current time on its port 4415. Any client can access it. To test the application start the server with java TimeServer. A window should open with the message TimServer running... Do not close the window. On XP machines use the RUN dialog telnet localhost 4415. On older platforms start telnet in another window. At the connect dialog enter localhost in the Host Name field and 4415 in the Port field

Remote Method Invocation (RMI)

Remote Method Invocation allows a Java object that executes on one machine to invoke a method of a Java object that executes on another machine. This permits the creation of distributed applications. The java.rmi and java.rmi.server packages provide the required objects to handle remote method invocation. RMI is illustrated with a simple client/server application that is built in steps. The application does a simple addition operation.

Step One: Compile Source Code

Note: Source code files for this example have been packed in jp7net.zip. Unpack them to a rmiProject directory.

AddServerIntf.java defines the remote interface that is provided by the server. It contains a method that takes two double arguments and returns a double sum. Remote interfaces must extend the Remote interface. Each method in the interface must throw (or trap) RemoteException exceptions.

AddServerImpl.java implements the remote interface. All remote objects must extend the UnicastRemoteObject.

AddServer.java contains the main program for the server. Its primary function is to update the RMI registry.

AddClient.java implements the client side of the application. It requires three command line arguments (IP address/name of the server and the two numbers to be added. The application forms an rmi URL.

Step Two: Generate Stubs and Skeleton

A stub is a Java object on the client machine which matches a skeleton object resident on the server. Note: Java 2 does not require stubs or skeletons. To generate stubs and skeletons, use the rmic AddServerImpl command to generate files called AddServerImpl_Skel.class and AddServerImpl_Stub.class. Be sure to have CLASSPATH pointed at the rmiProject directory.

Step Three: Install Files on Client and Server

Install the class files on their respective client or server machine. For testing purposes this may be the same one!

Step Four: Start the RMI Registry on the Server

First make sure that CLASSPATH includes the directory where you placed the files in step three. Then issue the start rmiregistry command. Note that a new window has been created. It must remain open until testing is complete.

Step Five: Start the Server

Issue the java AddServer command

Step Six: Start the Client

On your client machine issue the java AddClient server1 8 9 command. If you are testing with the server on the same machine as the client use java AddClient 127.0.0.1 8 9. The address 127.0.0.1 is the loopback address for any self-test connection.



JR's HomePage | Comments [jatutorh.htm:2009 03 07]