Pages

Java.net Package

Networking

Collection of interconnected autonomous or non-autonomous computers is known as network. Networking is a concept of connecting two or more computing devices together so that we can share resources. As a part of networking we write two types of programs. They are client side programming and server side programming. A client side programming is one which always makes a request to get the server from the server side program. A server side programming is one which receives client request, process the request and give response back to the client.



Networking Terminology

There is some networking terminologies given below:
  • IP Address
  • Protocol
  • Port Number
  • Server
  • Client
  • Medium

IP Address:

IP address is a unique number assigned to a node of a network to identify system uniquely. It is composed of  octets that range from 0 to 255.
ex: 192.168.0.1 

Protocol:

A protocol is a set of rules basically that is followed for communication. For example:
  • TCP
  • FTP
  • Telnet
  • SMTP
  • POP
  • http etc.

Port No

It is  a short integer which ranges from 0 to 65535. Out of all ports 0-1023 ports already reserved by predefined protocols. Port no is used to communicate between two processed whereas IP address is used to comminucate between two system.

Socket class

In order to develop the program at client side we must use the class Socket in java. A socket is simply an endpoint for communications between the machines. The Socket class can be used to create a socket. Commonly used methods of Socket class.

Constructor:
                 Socket (String hname, int Portno) throws UnknownHostException, IOException: This is used                                                                          for establishing the connection with server socket by passing the host name and port number of the server side program.
EX: Socket s = new Socket ("localhost", 7001);

Methods:
            public OutputStream getOutputStream (): This is used for writing the data to the server side                                                                                           program.
            public InputStream getInputStream (): This is used for receiving or reading the response givenby the                                                                         server side program.
            public void close (): This is used for closing socket or client communication with the server.


ServerSocket class

In order to develop the program at server side we must use the class ServerSocket. The ServerSocket class can be used to create a server socket. This object is used to establish communication with the clients.

Constructors:
                   ServerSocket (int portno) throws IOException: This is used for making the server side program                                                            to run at certain port number.

Methods:
              public Socket accept (): This is used for accepting socket data (client data).
              public OutputStream getOutputStream (): This is used for writing the data to the client side                                                                                             program.
              public InputStream getInputStream (): This is used for receiving of reading the response given by                                                                             the client side program.
              public void close (): This is used for closing of terminating server side program i.e, ServerSocket                                                  program.


Example of Socket Programming

//MyClient.java

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

public class MyClient
{
public static void main(String [] args) {
try
{
Socket s = new Socket ("localhost", 6666);
BufferedWriter pw = new BufferedWriter (new OutputStreamWriter (s.getOutputStream()));
pw.write("welcome to hungry4java.blogspot.com");
pw.flush();
pw.close();
s.close();
}
catch (Exception e)
{
System.out.println(e);
}
}
}

//MyServer.java

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

public class MyServer
{
public static void main(String [] args) {
try
{
ServerSocket ss = new ServerSocket(6666);
System.out.println("Waiting for client......");
Socket s = ss.accept(); //establishes connection
BufferedReader br = new BufferedReader (new InputStreamReader (s.getInputStream()));
String str = br.readLine();
System.out.println("message= "+str);
ss.close();
}
catch (Exception e)
{
System.out.println(e);
}
}



}


Java program which illustrates the concept of Socket and ServerSocket classes

//Server.java

 import java.io.*;

import java.net.*;


class Server

{

public static void main(String [] args) {

try

{

int pno = Integer.parseInt(args[0]);

ServerSocket ss = new ServerSocket(pno);

System.out.println("Server is ready");

while(true) 

{

Socket s = ss.accept();

BufferedReader br = new BufferedReader (new InputStreamReader (s.getInputStream()));

int num = Integer.parseInt(br.readLine());


System.out.println("Value of client= "+num);

int res = num * num;

PrintWriter pw = new PrintWriter(s.getOutputStream(), true);

pw.println(res);

}

}

catch (Exception e)

{

System.out.println(e);

}

}

}


//Client.java

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

class Client
{
public static void main(String [] args) 
{
try
{
String sname = args[0];
int pno = Integer.parseInt (args[1]);
Socket s = new Socket(sname, pno);
System.out.println("client connected to Server");
PrintWriter pw = new PrintWriter(s.getOutputStream(), true);

int num = Integer.parseInt(args[2]);
pw.println(Integer.toString(num));

BufferedReader br = new BufferedReader (new InputStreamReader(s.getInputStream()));
System.out.println("Result from server= "+br.readLine());
}
catch (Exception e)
{
System.out.println(e);
}
}
}



URL class

The URL class represents a URL. URL is an acronym for Uniform Resource Locator. It points to a resource  on the World Wide Web. For example:
                    
                                                     http://www.litindia.in/Gallery.html

A URL contains many information:
  • Protocol: In this case, http is the protocol.
  • Server name or IP Address: In this case, www.lit.com is the server name.
  • Port Number: It is  on optional attribute. If we write http://www.lit.com:80/sonoojaiswal/ , 80 is the port number.
  • File Name or directory name: In this case, Gallery.html is the file name.

Commonly used methods of URL class

  • public String getProtocol (): It returns the protocol of the URL.
  • public String getHost (): It returns the host name of the URL.
  • public String getPort (): It returns the Port Number of the URL.
  • public String getFile (): It returns the file name of the URL.

Example of URL

//URLDemo.java

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

public class URLDemo
{
public static void main(String args[])
{
try
{
URL url = new URL("http://www.hungry4java.blogspot.com");

System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("File Name: "+url.getFile());
}
catch (Exception e)
{
System.out.println(e);
}
}
}


URLConnection class

The URLConnection class represents a communication link between the URL and the application. This class can be used to read and write data to the specified resource referred by the URL.

The openConnection() method of URL class returns the object of URLConnection class.
Syntax:
         public URLConnection openConnection () throws IOException {}

Example of URLConnection ()

//DisplayData.java

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

public class DisplayDate
{
public static void main(String [] args) 
{
try
{
URL url = new URL("http://hungry4java.blogspot.com");
URLConnection urlcon = url.openConnection();

InputStream stream = urlcon.getInputStream();
int i;

while(i = stream.read())!=-1)
{
System.out.print((char)i);
}
}
catch (Exception e)
{
System.out.println(e);
}
}
}


InetAddress class

The java.net.InetAddress class represents an IP address. The InetAddress class provides methods to get the IP of  any host name.

Commonly used methods of InetAddress class

  • public static InetAddress getByName (String host) throws UnknownHostException: It returns the IP                                                  of the given host.
  • public static InetAddress getLocalHost () throws UnknownHostException: It returns the LocalHost IP                                                and name.
  • public String getHostName (): It returns the host name of the IP address.
  • public String getHostAddress (): It returns the IP address in string format.

Example of InetAddress keyword

//InetDemo.java

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

public class InetDemo
{
public static void main(String [] args) 
{
try
{
InetAddress ip = InetAddress.getByName("www.hungry4java.blogspot.com");

System.out.println("Host Name: "+ip.getHostName());
System.out.println("IP Address: "+ip.getHostAddress());
}
catch (Exception e)
{
System.out.println(e);
}
}
}


DatagramSocket and DatagramPacket (Networking)

The DatagramSocket and DatagramPacket classes are used for connection-less socket programming.

DatagramSocket class

The DatagramSocket class represents a connection-less socket for sending and receiving datagram packets. Datagram is basically an information but there is no gurantee of its content, arrival or arrival time.

Commonly used Constructors of DatagramSocket class

  • DatagramSocket () throws SocketException:  It  creates a datagram socket and bind it with the                                                                                 available Port Number on the localhost machine.
  • DatagramSocket (int port) throws SocketException: It creates a datagram socket and bind it with the                                                                                given port Number.
  • DatagramSocket (int port, InetAddress address) throws SocketException: It creates a datagram                                                             socket and binds it with the specified port number and host address.

DatagramPacket class

The DatagramPacket is message that can be sent or received. If you send multiple packets, it may arrive in any order. Moreover, packet delivery is not guaranteed.

Commonly used Constructors of DatagramPakcet class

  • DatagramPacket (byte[] barr, int length): It creates a datagram packet. This constructor is used to                                                                 receive the packets.
  • DatagramPacket (byte[] barr int length, InetAddress address, int port): It creates a DatagramPacket.                                                           This constructor is used to send the packets.

Example of sending DatagramPacket by DatagramSocket

//DSender.java

import java.net.*;

public class DSender
{
public static void main(String [] args)  throws Exception
{
DatagramSocket ds = new DatagramSocket();
String str = "Welcome to Learn java Graphics";
InetAddress ip = InetAddress.getByName("127.0.0.1");
DatagramPacket dp = new DatagramPacket(str.getByte(), str.length(), ip, 3000);
ds.send(dp);
ds.close();
}
}

//DReceiver.java

import java.net.*;

public class DReceiver
{
public static void main(String args[]) throws Exception
{
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];

DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
ds.close();
}
}



No comments:

Post a Comment