Thursday 18 August 2011

JAVA NETWORKING


INTRODUCTION:

Why Networked Java?

                                 Java is the first programming language designed from the ground up with networking in mind. As the global Internet continues to grow, Java is uniquely suited to build thenext generation of network applications. Java provides solutions to a number of problems—platform independence, security, and international character sets being the most  important—that are crucial to Internet applications, yet difficult to address in other languages. Together, these and other Java features allow web surfers to quickly download and execute untrusted programs from a web site without worrying that the program may spread a virus, steal their data, or crash their systems. Indeed, the intrinsic safety of a Java applet is far greater than that of shrink-wrapped software. One of the biggest secrets about Java is that it makes writing network programs easy. In fact, it is far easier to write network programs in Java than in almost any other language.
In short, it is easy for Java applications to send and receive data across the Internet. It is also possible for applets to communicate across the Internet, though they are limited by security restrictions.

What Can a Network Program Do?

1.      Retrieve Data and Display It
2.      Repeatedly Retrieve Data
3.      Send Data
4.      File storage
5.      Massively parallel computing

URL
URL is the acronym for Uniform Resource Locator. It is a reference (an address) to a resource on the Internet. The simplest way for a Java program to locate and retrieve data from the network is to use the URL class.  The following is an example of a URL which addresses the Java Web site hosted by Sun Microsystems: 

  http://www.google.com/

Here, http:// - protocal
           google - resource identifier


As in the previous diagram, a URL has two main components:
·           Protocol identifier
·           Resource name
Note that the protocol identifier and the resource name are separated by a colon and two forward slashes. The protocol identifier indicates the name of the protocol to be  used to fetch the resource. The example uses the Hypertext Transfer Protocol (HTTP), Other protocols include File Transfer Protocol (FTP), Gopher, File, and News.

The resource name is the complete address to the resource. The format of the esource name depends entirely on the protocol used, but for many protocols, including HTTP, the resource name contains one or more of the components listed in the following table

Host Name
The name of the machine on which the resource lives.
Filename
The pathname to the file on the machine.
Port Number
The port number to which to connect (typically optional).
Reference
A reference to a named anchor within a resource that usually identifies a specific location within a file (typically optional).
For many protocols, the host name and the filename are required, while the port number and reference are optional.

In your Java programs, you can create a URL object from a relative URL specification. For example, suppose you know two URLs at the Gamelan site:
http://www.gamelan.com/pages/Gamelan.game.html
http://www.gamelan.com/pages/Gamelan.net.html
You can create URL objects for these pages relative to their common base URL: http://www.gamelan.com/pages/ like this:
URL gamelan = new URL("http://www.gamelan.com/pages/");
URL gamelanGames = new URL(gamelan, "Gamelan.game.html");
URL gamelanNetwork = new URL(gamelan, "Gamelan.net.html");
Parsing a URL
The URL class provides several methods that let you query URL objects. You can get the protocol, authority, host name, port number, path, query, filename, and reference from a URL using these accessor methods:
public string Protocal()
Returns the protocol identifier component of the URL.
Public getAuthority()
Returns the authority component of the URL.
public string getHost ()
Returns the host name component of the URL.
Public int getPort()
Returns the port number component of the URL. The getPort method returns an integer that is the port number. If the port is not set, getPort returns -1.
public string getPath()
Returns the path component of this URL.
public string getQuery()
Returns the query component of this URL.
public string getFile()
Returns the filename component of the URL. The getFile method returns the same as getPath, plus the concatenation of the value of getQuery, if any.
public string getRef()
Returns the reference component of the URL.

The URL Class
public final class URL extends Object implements Serializable

Creating a URL
To create a URL ,you   construct instances of java.net.URL.
There are six constructors, differing in the information they require.  All these constructors throw a MalformedURLException if you try to create a URL for an unsupported protocol.

Constructing a URL from a string
The easiest way to create a URL object is from a String that represents the human-readable form of the URL address.
 
try {
URL u = new URL("http://www.macfaq.com/personal.html");
}
catch (MalformedURLException e) {
System.
}  
The URL object created above represents an absolute URL. An absolute URL contains all of the information necessary to reach the resource in question
Constructing a URL from its component parts
The second constructor builds a URL from three strings specifying the protocol, the hostname, and the file:
public URL(String protocol, String throws MalformedURLException

The file argument should begin with a slash, and include a path, a filename, and optionally a reference to a named anchor.
try {
URL u = new URL("http", "www.eff.org", "/blueribbon.html#intro");
}

catch (MalformedURLException e) {
// All VMs should recognize http
}
This creates a URL object that points to http://www.eff.org/blueribbon.html#intro, using the default port for the HTTP protocol (port 80). The file specification includes  reference to a named anchor.



Constructing relative URLs
A relative URL contains only enough information to reach the resource relative to (or in the context of) another URL. This constructor builds an absolute URL from a relative URL and a base URL: URL constructor  lets you create a URL object from another URL object (the base) and a relative URL specification.
The general form of this constructor is:
public URL(URL base, String relative) throws MalformedURLException

The first argument is a URL object that specifies the base of the new URL.
The second argument is a String that specifies the rest of the resource name relative to the base.  If baseURL is null, then this constructor treats relativeURL like an absolute URL specification

 Retrieving Data from a URL
The URL class has three methods (four in Java 1.3) to retrieve data from a URL; they are:
public final InputStream openStream( ) throws IOException
public URLConnection openConnection( ) throws IOException
public final Object getContent( ) throws IOException
public final Object getContent(Class[] classes)  throws IOException

public final InputStream openStream( ) throws IOException
After you've successfully created a URL, you can call the URL's openStream() method to get a stream from which you can read the contents of the URL. The openStream() method  returns a java.io.InputStreamobject, so reading from a URL is as easy as reading from an input stream.

public URLConnection openConnection( ) throws IOException
The openConnection( ) method opens a socket to the specified URL and returns a  URLConnection object. A URLConnection represents an open connection to a network resource. If the call fails, openConnection( ) throws an IOException.
try {
URL yahoo = new URL("http://www.yahoo.com/");
URLConnection yahooConnection = yahoo.openConnection();
yahooConnection.connect();
} catch (MalformedURLException e) 
{     // new URL()  failed
    . . .
} catch (IOException e) {               // openConnection() failed
    . . .
}

public final Object getContent( ) throws IOException
The getContent( ) method retrieves the data referenced by the URL and tries to make it into some type of object.

try {
URL u = new URL("http://mesola.obspm.fr/");
Object o = u.getContent( );
// cast the Object to the appropriate type
// work with the Object...
}
catch (Exception e) {
System.err.println(e);
}

public final Object getContent(Class[ ] classes) throws IOException
This overloaded variant of the getContent( ) method lets you choose what class you'd like the content returned as. The method will attempt to return the  URL's content in the order used in the array. For instance, if you'd prefer an HTML file to be returned as a String, but your second choice is a Reader and your third choice is an InputStream, you would write:
URL u = new URL("http://www.nwu.org");
Class[] types = new Class[3];
types[0] = String.class;
types[1] = Reader.class;
types[2] = InputStream.class;
Object o = u.getContent(types);

public boolean sameFile(URL other)
The sameFile( ) method tests whether two URL objects point to the same file. If they do, sameFile( ) returns true; otherwise, it returns false.

public String toExternalForm( )
The toExternalForm( ) method returns a human-readable String representing the URL.

The URLEncoder and URLDecoder Classes
Characters used in URLs must come from a fixed subset of ASCII, in particular:
The capital letters A-Z
The lowercase letters a-z
The digits 0-9
The punctuation characters - _ . ! ~ * ` (and , )
The characters : / & ? @ # ; $ + = % and , may also be used, but only for their specified purposes. If these characters occur as part of a filename, then they and all other characters should be encoded. 
The encoding used is very simple. Any characters that are not ASCII numerals, letters, or the punctuation marks specified earlier are represented by a percent sign followed by two hexadecimal digits giving the value for that character. Spaces are a special case because they're so common. They can be encoded as a plus sign (+). The plus sign itself is encoded