Latest News

New Summer Look :)










Java And Networking

 

Networking with Java

InetAddress

URL Basics

Creating new URLs

Querying URLs

Getting Data From a URL

Querying URLs

URL, Other Methods

Reading From a URL

Sockets for Clients

The Socket Class

Using Sockets

Sockets Exceptions

Sockets For Servers

Using Server Sockets

Quiz

Exercises

 


Networking with Java

Java is the first programming language designed with networking in mind. It is therefore uniquely suited for building network applications

Using the java.net package makes network programming easy. Much easier than in any other languages

The java.net package contains classes for IP, Sockets, DNS handling, URL


InetAddress

Creating new InetAddress objects:

1) public static InetAddress getByName(String host)
InetAddress iaddr = InetAddress.getByName("www.acm.org");

2) public static InetAddress[] getAllByName(String host)
InetAddress iaddr[] = InetAddress.getAllByName("x.xx.x");

3) public static InetAddress getLocalHost()
InetAddress iaddr = InetAddress.getLocalHost();

- If a host is not found a UnknownHostException is thrown

 

URL Basics

- Uniform Resource Locator - URL defined in RFC1738

- An URL is the standard way of addressing Internet resources

- An URL consists of 4 main parts: protocol , host , port , file

- URL Usage : protocol://host:port/file
e.g. : http://www.cs.nott.ac.uk:80/~azt/index.html

- Supported standard protocols in 1.1 are: http, ftp, news, mailto, gopher and file

 

Creating new URLs

1) public URL(String spec)
URL u1 = new URL("http://www.cs.nott.ac.uk/~azt/");

2) public URL(String protocol, String host, String file)
URL u2 = new URL("http", "www.cs.nott.ac.uk/~azt/","/java/");

3) public URL(String protocol, String host, int port, String file)
URL u3 = new URL("http","www.cs.nott.ac.uk/~azt",80,"/java/");

4) public URL(URL context, String spec)
URL u4 = new URL(u, "/java/");

- If an invalid URL is specified a MalformedURLException is thrown

 

Querying URLs

The URL class contains a number of methods for splitting URLs into different parts:

- public String getProtocol()

- public String getHost()

- public int getPort()

- public String getFile()

 

Getting Data From a URL


There are three methods in the URL class for retrieving data from a URL

1 public final InputStream openStream()
- returns a stream to the data

2 public URLConnection openConnection()
- is used to communicate directly with the server
- gives access to the raw data

3 public final Object getContent()
- tries to parse the data into an object representing the data based on the returned MIME-type. A content-handler for each type must exists but in JDK only a few are available: text/plain, text/generic, image/gif and image/jpeg


URL, Other Methods

  - public boolean sameFile(URL other), Compares to URLs to see if they point to the same file

- public boolean equals(Object obj), Compares to URL objects to see if they are the same

- public String toString(), Constructs a String representation of this URL by calling the toString() method in the corresponding stream content handler


Reading From a URL

 
import java.io.*;
import java.net.URL;

public class URLReader {
    
 public static void main(String args[]) {
  URL myURL;
  InputStreamReader myURLContent;
  int intValue;
  try {
   myURL = new URL("http://www.cs.nott.ac.uk");
   myURLContent = new InputStreamReader(myURL.openStream());
   intValue = myURLContent.read();	        
   while (intValue != -1) {
     System.out.print((char) intValue);
     intValue = myURLContent.read();
   }

   myURLContent.close();
  }
  catch (Exception e) {
    System.out.println("Error while opening URL");
  }              
 } // end main
     
} // end class

 

 

Sockets for Clients


Sockets allow applications to communicate

A socket performs seven basic operations

- 1.Connects to a remote host

- 2.Sends data

- 3.Receives data

- 4.Closes a connection

- 5.Binds to a port

- 6.Listens for incoming data

- 7.Accepts connections from remote machines on the bound port

There are two main types of application level sockets

- TCP - Transmission Control Protocol

- UDP - User Datagram Protocol


The Socket Class


public Socket(String host, int port)

public Socket(InetAddress address, int port)

Getting information about a socket :

public InetAddress getInetAddress(), returns the address to which the socket is connected

public int getPort(), returns the remote port to which this socket is connected

public int getLocalPort(), returns the local port to which this socket is bound


Using Sockets


Streaming data through a socket :

- public InputStream getInputStream()

- public OutputStream getOutputStream()

Closing a socket :

- public synchronized void close(), closes the socket and cleans up system resources. This is done automatically when a program exits but it is good practice
to do this in every program that no longer needs a connection.


Sockets Exceptions


BindException: Thrown if the socket tries to use a local port that is busy or if the program has not enough privileges to use that port

ConnectException: No connection to the remote host. No server running on that port

NoRouteToHostException: There is no path over the network to the remote host

SocketException: Something went wrong in the socket which is not covered by the above exceptions

 

Sockets for Servers


The difference between client sockets and server sockets is that the server sockets wait for an incoming connection

The basic life cycle of a server is

- 1. A new ServerSocket is created

- 2. The socket listens for incoming connections using the accept call which blocks

- 3.The server interacts with the client

- 4.The client and/or server closes the socket

- 5.The server returns to step 2

 

Using Server Sockets


Creating a server socket :

- public ServerSocket(int port)

Creates a server socket that listens on a local port :

- public ServerSocket(int port,int backlog)

Accepting and closing connections :

- public Socket accept() -> waits for connection
- public void close() -> closes the socket

Other methods :

- public InetAddress getInetAddress()->Get client address
- public int getLocalPort() -> Get the client local port


Quiz


1. Applet security restrictions only allow an applet to establish network connections to one host: the host from which it was downloaded. Suppose that you have an applet that needs to connect to another server. How do you proceed?

2. Both Sockets and RMI can be used to connect to remote machines, exchange data and share information. Can you think of any types of programs that are best suited for one of them?




Exercises


1. Write an application that connects to the specified URL, gets its contents and then checks if the links from that page actually exist. Use a TextField to allow the user to input the URL, a “GO!” button and a TextArea to display the results of your search. To do this, you’ll have to parse the URL content, finding any “<A HREF=“, “<IMG SRC=“ and “<applet code=“. To find out the link status try to open a stream to that connection

2. Improve on the previous exercise by providing a way to recursively test links on the specified URL. You may let the user define a maximum depth for your search

 

 


Online Java Training, Java And Networking


 
My other sites

Latest News

New Summer Look :)










Java And Networking

 

Networking with Java

InetAddress

URL Basics

Creating new URLs

Querying URLs

Getting Data From a URL

Querying URLs

URL, Other Methods

Reading From a URL

Sockets for Clients

The Socket Class

Using Sockets

Sockets Exceptions

Sockets For Servers

Using Server Sockets

Quiz

Exercises

 


Networking with Java

Java is the first programming language designed with networking in mind. It is therefore uniquely suited for building network applications

Using the java.net package makes network programming easy. Much easier than in any other languages

The java.net package contains classes for IP, Sockets, DNS handling, URL


InetAddress

Creating new InetAddress objects:

1) public static InetAddress getByName(String host)
InetAddress iaddr = InetAddress.getByName("www.acm.org");

2) public static InetAddress[] getAllByName(String host)
InetAddress iaddr[] = InetAddress.getAllByName("x.xx.x");

3) public static InetAddress getLocalHost()
InetAddress iaddr = InetAddress.getLocalHost();

- If a host is not found a UnknownHostException is thrown

 

URL Basics

- Uniform Resource Locator - URL defined in RFC1738

- An URL is the standard way of addressing Internet resources

- An URL consists of 4 main parts: protocol , host , port , file

- URL Usage : protocol://host:port/file
e.g. : http://www.cs.nott.ac.uk:80/~azt/index.html

- Supported standard protocols in 1.1 are: http, ftp, news, mailto, gopher and file

 

Creating new URLs

1) public URL(String spec)
URL u1 = new URL("http://www.cs.nott.ac.uk/~azt/");

2) public URL(String protocol, String host, String file)
URL u2 = new URL("http", "www.cs.nott.ac.uk/~azt/","/java/");

3) public URL(String protocol, String host, int port, String file)
URL u3 = new URL("http","www.cs.nott.ac.uk/~azt",80,"/java/");

4) public URL(URL context, String spec)
URL u4 = new URL(u, "/java/");

- If an invalid URL is specified a MalformedURLException is thrown

 

Querying URLs

The URL class contains a number of methods for splitting URLs into different parts:

- public String getProtocol()

- public String getHost()

- public int getPort()

- public String getFile()

 

Getting Data From a URL


There are three methods in the URL class for retrieving data from a URL

1 public final InputStream openStream()
- returns a stream to the data

2 public URLConnection openConnection()
- is used to communicate directly with the server
- gives access to the raw data

3 public final Object getContent()
- tries to parse the data into an object representing the data based on the returned MIME-type. A content-handler for each type must exists but in JDK only a few are available: text/plain, text/generic, image/gif and image/jpeg


URL, Other Methods

  - public boolean sameFile(URL other), Compares to URLs to see if they point to the same file

- public boolean equals(Object obj), Compares to URL objects to see if they are the same

- public String toString(), Constructs a String representation of this URL by calling the toString() method in the corresponding stream content handler


Reading From a URL

 
import java.io.*;
import java.net.URL;

public class URLReader {
    
 public static void main(String args[]) {
  URL myURL;
  InputStreamReader myURLContent;
  int intValue;
  try {
   myURL = new URL("http://www.cs.nott.ac.uk");
   myURLContent = new InputStreamReader(myURL.openStream());
   intValue = myURLContent.read();	        
   while (intValue != -1) {
     System.out.print((char) intValue);
     intValue = myURLContent.read();
   }

   myURLContent.close();
  }
  catch (Exception e) {
    System.out.println("Error while opening URL");
  }              
 } // end main
     
} // end class

 

 

Sockets for Clients


Sockets allow applications to communicate

A socket performs seven basic operations

- 1.Connects to a remote host

- 2.Sends data

- 3.Receives data

- 4.Closes a connection

- 5.Binds to a port

- 6.Listens for incoming data

- 7.Accepts connections from remote machines on the bound port

There are two main types of application level sockets

- TCP - Transmission Control Protocol

- UDP - User Datagram Protocol


The Socket Class


public Socket(String host, int port)

public Socket(InetAddress address, int port)

Getting information about a socket :

public InetAddress getInetAddress(), returns the address to which the socket is connected

public int getPort(), returns the remote port to which this socket is connected

public int getLocalPort(), returns the local port to which this socket is bound


Using Sockets


Streaming data through a socket :

- public InputStream getInputStream()

- public OutputStream getOutputStream()

Closing a socket :

- public synchronized void close(), closes the socket and cleans up system resources. This is done automatically when a program exits but it is good practice
to do this in every program that no longer needs a connection.


Sockets Exceptions


BindException: Thrown if the socket tries to use a local port that is busy or if the program has not enough privileges to use that port

ConnectException: No connection to the remote host. No server running on that port

NoRouteToHostException: There is no path over the network to the remote host

SocketException: Something went wrong in the socket which is not covered by the above exceptions

 

Sockets for Servers


The difference between client sockets and server sockets is that the server sockets wait for an incoming connection

The basic life cycle of a server is

- 1. A new ServerSocket is created

- 2. The socket listens for incoming connections using the accept call which blocks

- 3.The server interacts with the client

- 4.The client and/or server closes the socket

- 5.The server returns to step 2

 

Using Server Sockets


Creating a server socket :

- public ServerSocket(int port)

Creates a server socket that listens on a local port :

- public ServerSocket(int port,int backlog)

Accepting and closing connections :

- public Socket accept() -> waits for connection
- public void close() -> closes the socket

Other methods :

- public InetAddress getInetAddress()->Get client address
- public int getLocalPort() -> Get the client local port


Quiz


1. Applet security restrictions only allow an applet to establish network connections to one host: the host from which it was downloaded. Suppose that you have an applet that needs to connect to another server. How do you proceed?

2. Both Sockets and RMI can be used to connect to remote machines, exchange data and share information. Can you think of any types of programs that are best suited for one of them?




Exercises


1. Write an application that connects to the specified URL, gets its contents and then checks if the links from that page actually exist. Use a TextField to allow the user to input the URL, a “GO!” button and a TextArea to display the results of your search. To do this, you’ll have to parse the URL content, finding any “<A HREF=“, “<IMG SRC=“ and “<applet code=“. To find out the link status try to open a stream to that connection

2. Improve on the previous exercise by providing a way to recursively test links on the specified URL. You may let the user define a maximum depth for your search