HTML Markup | JavaScript | Java | 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 ip name to address conversion, 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 network objects will be described in the following material.

Internet Addresses

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.

The InetAddress class encapsulates ip address and domain name data. Static methods: getLocalHost(), getByName() and getAllByName(). Nonstatic methods: getAddress(), getHostAddress(), getHostName() and isMulticastAddress(). The following example shows how to use InetAddress:

Internet Streams

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

GetFile.java 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. Note: HTML files are best displayed using a Swing JEditorPane component.

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 fileGrab packaging project.

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.

jget and JGet2 are Java clones of the Wget GNU - C web file retrieval program that can retrieve a single file, files from a whitelist, or spider a site to a user selectable number of levels.

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

Sockets,Clients,Servers

A network socket is a standard interface that is either a connection-oriented stream (TCP/IP protocol) or a connectionless datagram packet (UDP protocol). Sockets use IP address extensions or ports to connect to servers. Port numbers below 1024 are reserved for specific services such as FTP and telnet. You can use Sockets.com or google Well-Known Port Numbers to find the port number for a service.

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.

Client Stream Sockets

The java.net package provides Socket objects for network clients at the TCP/IP level. Establishing a stream client involves four steps:

  1. Create a new socket with a server address and a port number
  2. Create inputstream and outputstream objects
  3. Process stream data
  4. Close the streams

Whois.java accesses a single directory service that provides information about a specific host. It makes a socket connection to arin.net (the registrar for many american sites), sets a timeout and establishes a stream to access the data. Once compiled, test Whois with java Whois amazon.com. Better utilities such as the one at freecode either select the registrar based on input domain name or spider through several registrars. This is an excellant project for a budding craftsman.

Server Stream Sockets

The java.net package provides ServerSocket objects for servers at the TCP/IP level. Establishing a stream server involves five steps:

  1. Create a new socket with port number and max number of clients
  2. Set a socket connect for a client using the accept() method
  3. Create inputstream and outputstream objects
  4. Process stream data
  5. Close the streams

TimeServer.java 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 will open with the message TimeServer 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. kryonet is a working server/client project provided by Google.

Here is a simple client/server remote method invocation demo that executes a simple math operation. For a more up to date version which includes Security Management refer to Ryerson Uni's example. The complete application is built using the following steps:

Step One: Fetch, Unpack and Compile Source Code

Fetch the zipped source code, unpack it and move the following four files to a rmiProject directory folder. Compile each of the four files.

AddServerIntf.java defines the remote interface that is provided by the server. Remote interfaces must extend the Remote interface. Each method in the interface must throw (or trap) RemoteException exceptions.

AddServerImpl.java implements the remote interface. It contains a method that takes two double arguments and returns a double sum. 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

Note: Java 2 does not require stubs or skeletons. This step is only required if Java 1.4 compatibility is required

A stub is a Java object on the client machine which matches a skeleton object resident on the server. 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.

Tutorial Source Code

Obtain source for InetAddressTest, GetFile, fileGrab, WhoIs, TimeServer, AddServerInf, AddServerImpl, AddServer and AddClient here.



JR's HomePage | Comments [jatutorh.htm:2013 04 24]