Introduction to Network programming in JAVA

NETWORKING

Consider a situation in which a program needs to access a resource, say a file. If the required file resides in the same system as the program, then it can execute without any problem. If the file is in another system, some mechanism is needed to connect to that system and retrieve the resource (file) and then execute. Java provides support for such network programming (accessing networked resources) using the classes defined in the java.net package.

The java.net package provides support for the two common network protocols:
§  TCP: TCP stands for Transmission Control Protocol, which allows for reliable communication between two applications. TCP is typically used over the Internet Protocol, which is referred to as TCP/IP.
§  UDP: UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets of data to be transmitted between applications.

The classes contained in the java.net package are:

1.    InetAddress
2.    ContentHandler
3.    URI
4.    URL
5.    URLConnection
6.    URLClassLoader
7.    HttpURLConnection
8.    Proxy
9.    Socket
10. ServerSocket
11. SocketAddress
12. SocketImpl
13. DatagramPacket
14. DatagramSocket

InetAddress Class Methods:

This class represents an Internet Protocol address. The InetAddress class is used to encapsulate both the numerical IP address and the domain name for that address. You interact with this class by using the name of an IP host, which is more convenient and understandable than its IP address.

Important methods of this class:
§  static InetAddress getByAddress(String host, byte[] addr)
o   Create an InetAddress based on the provided host name and IP address
§  static InetAddress getByName(String host)
o   Determines the IP address of a host, given the host's name.
§  String getHostAddress()
o   Returns the IP address string in textual presentation
§  String getHostName()
o   Gets the host name for this IP address
§  static InetAddress InetAddress getLocalHost()
o   Returns the local host
§  String toString()
o   Converts this IP address to a String.

// Demonstrate InetAddress.

import java.net.*;

class IA
{
    public static void main(String args[]) throws UnknownHostException
    {
          InetAddress Address = InetAddress.getLocalHost();
          System.out.println("Address : "+Address);
          String hostname = Address.getHostName();
          System.out.println("Host name : "+hostname);
          Address = InetAddress.getByName(hostname);
          System.out.println("Address : " + Address);
     }
}


URL

World Wide Web – The Web is a loose collection of higher-level protocols and file formats, all unified in a web browser. The Uniform Resource Locator (URL) is a powerful mechanism to locate all of the resources of the Net. Within Java’s network class library, the URL class provides a simple, concise API to access information across the Internet using URLs.

All URLs share the same basic format, although some variation is allowed. Here are two examples:

A URL specification is based on four components.
1.    The first is the protocol to use, separated from the rest of the locator by a colon (:). Common protocols are HTTP, FTP, gopher, and file
2.    The second component is the host name or IP address of the host to use; this is delimited on the left by double slashes (//) and on the right by a slash (/) or optionally a colon (:).
3.    The third component, the port number, is an optional parameter, delimited on the left from the host name by a colon (:) and on the right by a slash (/). (It defaults to port 80, the predefined HTTP port; thus, “:80” is redundant.)
4.    The fourth part is the actual file path. Most HTTP servers will append a file named index.html or index.htm to URLs that refer directly to a directory resource. Thus, http://www.google.com/ is the same as http://www.google.com:80/index.htm.


Java’s URL class has several constructors; each can throw a MalformedURLException.
1.    URL(String urlSpecifier) throws MalformedURLException
2.    URL(String protocolName, String hostName, int port, String path) throws MalformedURLException
3.    URL(String protocolName, String hostName, String path) throws MalformedURLException
4.    URL(URL urlObj, String urlSpecifier) throws MalformedURLException

Example:

// Demonstrate URL.

import java.net.*;

class URLDemo
{
public static void main(String args[]) throws MalformedURLException
{
      URL hp = new URL("https://www.google.co.in/?gws_rd=ssl#q=java+complete+reference");
      System.out.println("Protocol: " + hp.getProtocol());
      System.out.println("Port: " + hp.getPort());
      System.out.println("Host: " + hp.getHost());
      System.out.println("File: " + hp.getFile());
      System.out.println("Ext:" + hp.toExternalForm());
}
}


Output:
C:\Javapgms\Ntking>javac URLDemo.java
C:\Javapgms\Ntking>java URLDemo
Protocol: https
Port: -1
Host: www.google.co.in
File: /?gws_rd=ssl
Ext:https://www.google.co.in/?gws_rd=ssl#q=java+complete+reference
C:\Javapgms\Ntking>

// Notice that the port is –1; this means that a port was not explicitly set.


Socket Programming

At the core of Java’s networking support is the concept of a socket. A socket identifies an endpoint in a network. It provides the communication mechanism between two computers.

A client program creates a socket on its end of the communication and attempts to connect that socket to a server. When the connection is made, the server creates a socket object on its end of the communication. The client and server can now communicate by writing to and reading from the socket.

The java.net.Socket class represents a socket, and the java.net.ServerSocket class provides a mechanism for the server program to listen for clients and establish connections with them.
Steps to establish a connection between two computers using sockets:
1. The server instantiates a ServerSocket object, denoting which port number communication is to occur on.
2.    The server invokes the accept() method of the ServerSocket class. This method waits until a client connects to the server on the given port.
3.    After the server is waiting, a client instantiates a Socket object, specifying the server name and port number to connect to.
4.  The constructor of the Socket class attempts to connect the client to the specified server and port number. If communication is established, the client now has a Socket object capable of communicating with the server.
5.    On the server side, the accept() method returns a reference to a new socket on the server that is connected to the client's socket.

After the connections are established, communication can occur using I/O streams. Each socket has both an OutputStream and an InputStream. The client's OutputStream is connected to the server's InputStream, and the client's InputStream is connected to the server's OutputStream.

TCP is a two way communication protocol, so data can be sent across both streams at the same time..


ServerSocket Class Methods:

The java.net.ServerSocket class is used by server applications to obtain a port and listen for client requests
§  public ServerSocket(int port) throws IOException
o   Attempts to create a server socket bound to the specified port. An exception occurs if the port is already bound by another application
§  public int getLocalPort()
o   Returns the port that the server socket is listening on. This method is useful if you passed in 0 as the port number in a constructor and let the server find a port for you
§  public Socket accept() throws IOException
o   Waits for an incoming client. This method blocks until either a client connects to the server on the specified port or the socket times out, assuming that the time-out value has been set using the setSoTimeout() method. Else, this method blocks indefinitely
§  public void setSoTimeout(int timeout)
o   Sets the time-out value for how long the server socket waits for a client during the accept().
§  public void bind(SocketAddress host, int backlog)
o   Binds the socket to the specified server and port in the SocketAddress object.

Socket Class Methods:

§  public Socket(String host, int port) throws UnknownHostException, IOException.
o   This method attempts to connect to the specified server at the specified port. If this constructor does not throw an exception, the connection is successful and the client is connected to the server.
§  public Socket(String host, int port, InetAddress localAddress, int localPort) throws IOException.
o   Connects to the specified host and port, creating a socket on the local host at the specified address and port.
§  public void connect(SocketAddress host, int timeout) throws IOException
o   This method connects the socket to the specified host. This method is needed only when you instantiated the Socket using the no-argument constructor
§  public InetAddress getInetAddress()
o   This method returns the address of the other computer that this socket is connected to.
§  public int getPort()
o   Returns the port the socket is bound to on the remote machine
§  public int getLocalPort()
o   Returns the port the socket is bound to on the local machine
§  public SocketAddress getRemoteSocketAddress()
o   Returns the address of the remote socket
§  public InputStream getInputStream() throws IOException
o   Returns the input stream of the socket. The input stream is connected to the output stream of the remote socket
§  public OutputStream getOutputStream() throws IOException
o   Returns the output stream of the socket. The output stream is connected to the input stream of the remote socket
§  public void close() throws IOException
o   Closes the socket, which makes this Socket object no longer capable of connecting again to any server



TCP/IP Client Sockets

TCP/IP sockets are used to implement reliable, bidirectional, persistent, point-to-point, stream-based connections between hosts on the Internet. A socket can be used to connect Java’s I/O system to other programs that may reside either on the local machine or on any other machine on the Internet.

There are two kinds of TCP sockets in Java. One is for servers, and the other is for clients.
The ServerSocket class is designed to be a “listener,” which waits for clients to connect before doing anything. Thus, ServerSocket is for servers.

The Socket class is for clients. It is designed to connect to server sockets and initiate protocol exchanges. Because client sockets are the most commonly used by Java applications, they are examined here.

The creation of a Socket object implicitly establishes a connection between the client and server.

The following program provides a simple Socket example.                 
 
// Client program

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

public class Cli
{
    public static void main(String[] args) throws IOException
     {
          Socket s = new Socket(InetAddress.getLocalHost(), 100);
          BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream()));
          String str = br.readLine();
          System.out.println(str);
          System.exit(0);
    }
}

// Server Program
import java.io.*;
import java.net.*;

public class Svr
{
     public static void main(String[] args) throws IOException
     {
          ServerSocket ss = new ServerSocket(100);
          Socket s = new Socket();
        try
          {
              while (true)
              {
                   s = ss.accept();
                   PrintWriter out = new PrintWriter(s.getOutputStream(), true);
                   out.println("Welcome");
             }
        }
          catch(Exception e)
          {}
        finally
          {
              s.close();
              ss.close();
        }
    }
}



 Datagrams

UDP is a connectionless protocol used for unreliable data transfer between two machines in the form of datagrams. Once the datagram has been released to its intended target, there is no assurance that it will arrive or even that someone will be there to receive it. Likewise, when the datagram is received, there is no assurance that it hasn’t been damaged in transit or that whoever sent it is still there to receive a response.

Java implements datagrams on top of the UDP protocol by using two classes:
1.    DatagramPacket object is the data container,
2.    DatagramSocket – mechanism to send/receive the DatagramPackets.

DatagramSocket

DatagramSocket defines four public constructors. They are shown here:
§  DatagramSocket( ) throws SocketException
§  DatagramSocket(int port) throws SocketException
§  DatagramSocket(int port, InetAddress ipAddress) throws SocketException
§  DatagramSocket(SocketAddress address) throws SocketException

The first creates a DatagramSocket bound to any unused port on the local computer. The second creates a DatagramSocket bound to the port specified by port. The third constructs a DatagramSocket bound to the specified port and InetAddress. The fourth constructs a DatagramSocket bound to the specified SocketAddress. (SocketAddress is an abstract class that is implemented by the concrete class InetSocketAddress. InetSocketAddress encapsulates an IP address with a port number. )

DatagramSocket defines many methods. Two of the most important are send( ) and receive( ), which are shown here:
§  void send(DatagramPacket packet) throws IOException
o   sends packet to the port specified by packet.
§  void receive(DatagramPacket packet) throws IOException
o   waits for a packet to be received from the port specified by packet and returns the result.

DatagramPacket

DatagramPacket defines several constructors. Four are shown here:
  • DatagramPacket(byte data[ ], int size)
  • DatagramPacket(byte data[ ], int offset, int size)
  • DatagramPacket(byte data[ ], int size, InetAddress ipAddress, int port)
  • DatagramPacket(byte data[ ], int offset, int size, InetAddress ipAddress, int port)

The first constructor specifies a buffer that will receive data and the size of a packet. It is used for receiving data over a DatagramSocket. The second form allows you to specify an offset into the buffer at which data will be stored. The third form specifies a target address and port, which are used by a DatagramSocket to determine where the data in the packet will be sent. The fourth form transmits packets beginning at the specified offset into the data.

A Datagram Example

The following example implements a very simple networked communications client and server. Messages are typed into the window at the server and written across the network to the client side, where they are displayed.

// Demonstrate datagrams.
// Server Program

import java.net.*;

class Dsvr
{
     public static int serverPort = 998;
     public static int clientPort = 999;
     public static int buffer_size = 1024;
     public static DatagramSocket ds;
     public static byte buffer[] = new byte[buffer_size];
    
     public static void TheServer() throws Exception
     {
          int pos=0;
          while (true)
          {
              int c = System.in.read();
              switch (c)
              {
                   case '*':        System.out.println("Server Quits.");
                                      return;
                   case '\n':       ds.send(new DatagramPacket(buffer,pos,
InetAddress.getLocalHost(), clientPort));
                                      pos=0;
                                      break;
                   default:        buffer[pos++] = (byte) c;
              }
          }
     }
    
     public static void main(String args[]) throws Exception
     {
          ds = new DatagramSocket(serverPort);
          TheServer();
     }
}

// Client Program

import java.net.*;

class Dcli
{
     public static int serverPort = 998;
     public static int clientPort = 999;
     public static int buffer_size = 1024;
     public static DatagramSocket ds;
     public static byte buffer[] = new byte[buffer_size];
    
     public static void TheClient() throws Exception
     {
          while(true)
          {
              DatagramPacket p = new DatagramPacket(buffer, buffer.length);
              ds.receive(p);
              System.out.println(new String(p.getData(), 0, p.getLength()));
          }
     }

     public static void main(String args[]) throws Exception
     {
          ds = new DatagramSocket(clientPort);
          TheClient();
     }
}

Anything that is typed in the server window will be sent to the client window after a newline is received.

No comments:

Post a Comment

Don't be a silent reader...
Leave your comments...

Anu