Monday, 13 April 2015

Java Networking

Networking:
Networking is a concept of connecting two or more computing devices together so that we can share resources.
Advantage:
  • sharing resources
  • centralize software management


Do You Know ?
  • How to perform connection-oriented Socket Programming in networking ?
  • How to display the data of any online web page ?
  • How to get the IP address of any host name e.g. www.google.com ?
  • How to perform connection-less socket programming in networking ?
What we will learn in Networking Tutorial ?
  • Networking and Networking Terminology
  • Socket Programming (Connection-oriented)
  • URL class
  • Displaying data of a webpage by URLConnection class
  • InetAddress class
  • DatagramSocket and DatagramPacket (Connection-less)

Networking Terminology:
There are some networking terminologies given below:
  • IP Address
  • Protocol
  • Port Number
  • MAC Address
  • Connection-oriented and connectionless protocol
  • Socket
IP Address:
IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is composed of octets that range from 0 to 255.
Protocol:
A protocol is a set of rules basically that is followed for communication. For example:
  • TCP
  • FTP
  • Telnet
  • SMTP
  • POP etc.

Java Socket Programming

Java Socket programming is used for communication between the applications running on different JRE.
Java Socket programming can be connection-oriented or connection-less.
Socket and ServerSocket classes are used for connection-oriented socket programming and DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
The client in socket programming must know two information:
  1. IP Address of Server, and
  2. Port number.

Socket class

A socket is simply an endpoint for communications between the machines. The Socket class can be used to create a socket.

Important methods

Method
Description
1) public InputStream getInputStream()
returns the InputStream attached with this socket.
2) public OutputStream getOutputStream()
returns the OutputStream attached with this socket.
3) public synchronized void close()
closes this socket

ServerSocket class

The ServerSocket class can be used to create a server socket. This object is used to establish communication with the clients.

Important methods

Method
Description
1) public Socket accept()
returns the socket and establish a connection between server and client.
2) public synchronized void close()
closes the server socket.

Example of Java Socket Programming

Let's see a simple of java socket programming in which client sends a text and server receives it.
File: MyServer.java
1.    import java.io.*;  
2.    import java.net.*;  
3.    public class MyServer {  
4.    public static void main(String[] args){  
5.    try{  
6.    ServerSocket ss=new ServerSocket(6666);  
7.    Socket s=ss.accept();//establishes connection   
8.    DataInputStream dis=new DataInputStream(s.getInputStream());  
9.    String  str=(String)dis.readUTF();  
10. System.out.println("message= "+str);  
11. ss.close();  
12. }catch(Exception e){System.out.println(e);}  
13. }  
14. }  
File: MyClient.java
1.    import java.io.*;  
2.    import java.net.*;  
3.    public class MyClient {  
4.    public static void main(String[] args) {  
5.    try{      
6.    Socket s=new Socket("localhost",6666);  
7.    DataOutputStream dout=new DataOutputStream(s.getOutputStream());  
8.    dout.writeUTF("Hello Server");  
9.    dout.flush();  
10. dout.close();  
11. s.close();  
12. }catch(Exception e){System.out.println(e);}  
13. }  

14. }  

To execute this program open two command prompts and execute each program at each command prompt as displayed in the below figure.
After running the client application, a message will be displayed on the server console.




Example of Java Socket Programming (Read-Write both side)

In this example, client will write first to the server then server will receive and print the text. Then server will write to the client and client will receive and print the text. The step goes on.
File: MyServer.java
1.    import java.net.*;  
2.    import java.io.*;  
3.    class MyServer{  
4.    public static void main(String args[])throws Exception{  
5.    ServerSocket ss=new ServerSocket(3333);  
6.    Socket s=ss.accept();  
7.    DataInputStream din=new DataInputStream(s.getInputStream());  
8.    DataOutputStream dout=new DataOutputStream(s.getOutputStream());  
9.    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));  
10.   
11. String str="",str2="";  
12. while(!str.equals("stop")){  
13. str=din.readUTF();  
14. System.out.println("client says: "+str);  
15. str2=br.readLine();  
16. dout.writeUTF(str2);  
17. dout.flush();  
18. }  
19. din.close();  
20. s.close();  
21. ss.close();  
22. }}  
File: MyClient.java
1.    import java.net.*;  
2.    import java.io.*;  
3.    class MyClient{  
4.    public static void main(String args[])throws Exception{  
5.    Socket s=new Socket("localhost",3333);  
6.    DataInputStream din=new DataInputStream(s.getInputStream());  
7.    DataOutputStream dout=new DataOutputStream(s.getOutputStream());  
8.    BufferedReader br=new BufferedReader(new InputStreamReader(System.in));  
9.      
10. String str="",str2="";  
11. while(!str.equals("stop")){  
12. str=br.readLine();  
13. dout.writeUTF(str);  
14. dout.flush();  
15. str2=din.readUTF();  
16. System.out.println("Server says: "+str2);  
17. }  
18.   
19. dout.close();  
20. s.close();  
21. }}  


Java URL

The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator. It points to a resource on the World Wide Web. For example:
1.    http://www.mdurohtak.com.com/java-tutorial  
A URL contains many information:
  1. Protocol: In this case, http is the protocol.
  2. Server name or IP Address: In this case, www.mdurohtak.com.com is the server name.
  3. Port Number: It is an optional attribute. If we write http//ww.mdurohtak.com.com:80/sonoojaiswal/ , 80 is the port number. If port number is not mentioned in the URL, it returns -1.
  4. File Name or directory name: In this case, index.jsp is the file name.

Commonly used methods of Java URL class

The java.net.URL class provides many methods. The important methods of URL class are given below.
Method
Description
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.
public URLConnection openConnection()
it returns the instance of URLConnection i.e. associated with this URL.

Example of Java URL class

1.    //URLDemo.java  
2.    import java.io.*;  
3.    import java.net.*;  
4.    public class URLDemo{  
5.    public static void main(String[] args){  
6.    try{  
7.    URL url=new URL("http://www.mdurohtak.com.com/java-tutorial");  
8.      
9.    System.out.println("Protocol: "+url.getProtocol());  
10. System.out.println("Host Name: "+url.getHost());  
11. System.out.println("Port Number: "+url.getPort());  
12. System.out.println("File Name: "+url.getFile());  
13.   
14. }catch(Exception e){System.out.println(e);}  
15. }  
16. }  
Output:
       Protocol: http
       Host Name: www.mdurohtak.com.com
       Port Number: -1
       File Name: /java-tutorial



Java URLConnection class

The Java 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.

How to get the object of URLConnection class

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

Displaying source code of a webpage by URLConnecton class

The URLConnection class provides many methods, we can display all the data of a webpage by using the getInputStream() method. The getInputStream() method returns all the data of the specified URL in the stream that can be read and displayed.

Example of Java URLConnecton class

1.    import java.io.*;  
2.    import java.net.*;  
3.    public class URLConnectionExample {  
4.    public static void main(String[] args){  
5.    try{  
6.    URL url=new URL("http://www.mdurohtak.com.com/java-tutorial");  
7.    URLConnection urlcon=url.openConnection();  
8.    InputStream stream=urlcon.getInputStream();  
9.    int i;  
10. while((i=stream.read())!=-1){  
11. System.out.print((char)i);  
12. }  
13. }catch(Exception e){System.out.println(e);}  
14. }  
15. }  


Java HttpURLConnection class

The Java HttpURLConnection class is http specific URLConnection. It works for HTTP protocol only.
By the help of HttpURLConnection class, you can information of any HTTP URL such as header information, status code, response code etc.
The java.net.HttpURLConnection is subclass of URLConnection class.

How to get the object of HttpURLConnection class

The openConnection() method of URL class returns the object of URLConnection class. Syntax:
1.    public URLConnection openConnection()throws IOException{}  
You can typecast it to HttpURLConnection type as given below.
1.    URL url=new URL("http://www.mdurohtak.com");    
2.    HttpURLConnection huc=(HttpURLConnection)url.openConnection();  

Java HttpURLConnecton Example

1.    import java.io.*;    
2.    import java.net.*;    
3.    public class HttpURLConnectionDemo{    
4.    public static void main(String[] args){    
5.    try{    
6.    URL url=new URL("http://www.mdurohtak.com.com/java-tutorial");    
7.    HttpURLConnection huc=(HttpURLConnection)url.openConnection();  
8.    for(int i=1;i<=8;i++){  
9.    System.out.println(huc.getHeaderFieldKey(i)+" = "+huc.getHeaderField(i));  
10. }  
11. huc.disconnect();   
12. }catch(Exception e){System.out.println(e);}    
13. }    
14. }    
Output:
Date = Wed, 10 Dec 2014 19:31:14 GMT
Set-Cookie = JSESSIONID=D70B87DBB832820CACA5998C90939D48; Path=/
Content-Type = text/html
Cache-Control = max-age=2592000
Expires = Fri, 09 Jan 2015 19:31:14 GMT
Vary = Accept-Encoding,User-Agent
Connection = close
Transfer-Encoding = chunked


Java InetAddress class

Java InetAddress class represents an IP address. The java.net.InetAddress class provides methods to get the IP of any host name for example www.mdurohtak.com.com, www.google.com, www.facebook.com etc.

Commonly used methods of InetAddress class

Method
Description
public static InetAddress getByName(String host) throws UnknownHostException
it returns the instance of InetAddress containing LocalHost IP and name.
public static InetAddress getLocalHost() throws UnknownHostException
it returns the instance of InetAdddress containing local host name and address.
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 Java InetAddress class

Let's see a simple example of InetAddress class to get ip address of www.mdurohtak.com.com website.
1.    import java.io.*;  
2.    import java.net.*;  
3.    public class InetDemo{  
4.    public static void main(String[] args){  
5.    try{  
6.    InetAddress ip=InetAddress.getByName("www.mdurohtak.com.com");  
7.      
8.    System.out.println("Host Name: "+ip.getHostName());  
9.    System.out.println("IP Address: "+ip.getHostAddress());  
10. }catch(Exception e){System.out.println(e);}  
11. }  
12. }  
Output:
Host Name: www.mdurohtak.com.com
IP Address: 206.51.231.148


Java DatagramSocket and DatagramPacket

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

Java DatagramSocket class

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

Commonly used Constructors of DatagramSocket class

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

Java DatagramPacket class

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

Commonly used Constructors of DatagramPacket 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 datagram packet. This constructor is used to send the packets.

Example of Sending DatagramPacket by DatagramSocket

1.    //DSender.java  
2.    import java.net.*;  
3.    public class DSender{  
4.      public static void main(String[] args) throws Exception {  
5.        DatagramSocket ds = new DatagramSocket();  
6.        String str = "Welcome java";  
7.        InetAddress ip = InetAddress.getByName("127.0.0.1");  
8.         
9.        DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);  
10.     ds.send(dp);  
11.     ds.close();  
12.   }  
13. }  

Example of Receiving DatagramPacket by DatagramSocket

1.    //DReceiver.java  
2.    import java.net.*;  
3.    public class DReceiver{  
4.      public static void main(String[] args) throws Exception {  
5.        DatagramSocket ds = new DatagramSocket(3000);  
6.        byte[] buf = new byte[1024];  
7.        DatagramPacket dp = new DatagramPacket(buf, 1024);  
8.        ds.receive(dp);  
9.        String str = new String(dp.getData(), 0, dp.getLength());  
10.     System.out.println(str);  
11.     ds.close();  
12.   }  
13. }  


1 comment:

Access attributes in component

NOTE: To access an attribute in a  component , use expressions as  {! v.<Attribute Name>} . ----------------------------------------...