At the end of the chapter, you will be able to understand and use
Java has been specially created for networking. What do we mean by this? Java supports a package called java.net which defines several methods for connecting and retrieving files by using common web-based protocols. Java also allows us to create unix-like sockets and allows us to implement TCP/IP sockets.
In the previous chapter on Java IO programming, you have been introduced to Input and Output Stream. By attaching those stream files with networking protocols, you can write to files on the Internet and retrieve data from files over the Internet as if you are writing files on to a disk.
This chapter covers the basics of networking such as TCP/IP protocols and its implementation through TCP/IP and datagrams. URL connections and Inet addressing mechanisms are also presented. Client server application employing TCP/IPs and sockets are discussed.
Networking is the ability to connect to the Internet from our stand-alone applications or Applets. The classes required for this interconnection are available in java.net package. This package provides methods for creating sockets and file retrieval from any other networked cooperating system using web protocols. By attaching streaming classes with these network socket classes, writing and reading data to and from the Internet becomes easy.
There are two terms closely connected with java programming: Internet and World Wide Web (www). They are NOT synonymous, and they are NOT the same.
Network is a collection of computers that is either homogenous or heterogeneous.
The Internet is a collection or grouping together of networks. We can say that the Internet is a network of networks, comprising of millions of computers. These computers communicate with each other using Internet protocols.
World Wide Web (WWW) is a way of accessing information on the Internet. It uses HTTP to exchange data amongst communicating computers. The services provided by www uses Internet browsers such as Internet Explorer (IE), FireFox, Google Chrome, etc. The information is exchanged using HTTP and web pages. Web page is a place where required information is stored. Web pages are linked through hyperlinks. www is a method of Internet to exchange data over Internet.
Computers running on the Internet communicate with each other using either the Transmission Control Protocol (TCP) or the User Datagram Protocol (UDP).
A protocol is a set of rules to be followed by cooperating systems on the Internet for transferring data from one system to another system. TCP/IP, i.e., Transmission Control Protocol and Internet Protocol, are standard protocols to be used for transmission of data.
TCP/IP is a connection-oriented and reliable service.
Figure 22.1 TCP/UDP functionality
Figure 22.2 IP layer encapsulation of packet in a frame
Figure 22.3 TCP/IP model layers
UDP is a connection-less service. It means communication is not guaranteed between two applications. Delivery is not important and is not guaranteed. It is mostly used in transmission of video and audio, etc., where elaborate error detection and correction are not required and little bit of data missing cannot make perceptible differences.
We can obtain Internet address of any web site by using InetAddress class of java.net package. InetAddress class supports the following methods:
static InetAddress getByName (String hostName) throwsUnknownHostException
static InetAddress[] getAllByName (String hostName) throwsUnknownHostException returns all addresses that a particular web site name is representing.
static InetAddress getLocalHost() throwsUnknownHostException
Example 22.1: InetAddressDemo.java Write a Program to Get Inetaddresses and Local Host Name for a Specified Web Site
// This program requires Internet connection 1. package com.oops.chap22; 2. import java.io.*; 3. import java.net.*; 4. import java.util.*;// for scanner class 5. public class InetAddressDemo { 6. public static void main(String[] args)throws IOException { 7. String websitename; 8. Scanner scn=new Scanner(System.in); 9. System.out.print(“Enter WebSite Name :“); 10. websitename=scn.next(); 11. try{ 12. InetAddress ipadd=InetAddress.getByName(websitename); 13. System.out.println(“ The IP address obtained from Internet is : “+ ipadd); 14. }catch(UnknownHostException e) 15. { System.out.println(“Web Site NOT found”);} 16. }//end of main 17. }//end of class OUTPUT : Enter WebSite Name :www.google.com The IP address obtained from Internet is : www.google.com/209.85. 221.104 2 nd Run Enter WebSite Name :www.vasappanavara.org The IP address obtained from Internet is : www.vasappanavara.org/ 74.86.158.226
Line No. 12: | obtains the name of the web site by calling static method getByName() by creating object ipadd to InetAddress class. Line No 13 displays the result. |
Line No. 14: | catches (UnknownHostException e) |
Uniform Resource Locator (URL) has been created to get the information from the net, no matter which protocol has been employed to create it. We are aware that www is a collection of several protocols like HTTP/FTP/finger/whois. URL is a modern way to acquire information from the Internet. URLa class provides methodologies to access information using URL.
URL Constructors
URL Methods
URL: How to Set It to Work?
byte buffArray[ ] = new byte[1024];
while((i = inputstream.read(buffArray)) != -1) {
System.out.write(buffArray, 0, i);}
These concepts are shown in our next example.
Example 22.2: InetAddressDemo.java Write a Program to Get InetAddresses and Local Host Name for a Specified Web Site
//This program need Internet Connection
import java.io.*;
import java.net.*;
import java.util.*;// for scanner class
public class URLDemo {
public static void main(String[] args)throws IOException {
String websitename;
Scanner scn=new Scanner(System.in);
System.out.print(“Enter WebSite Name :”);
websitename=scn.next();
try{
URL myurl = new URL(websitename);
// Obtain input stream
InputStream inputstream = myurl.openStream();
// Read and display data from URL
byte buffArray[] = new byte[1024];
int i;
while((i = inputstream.read(buffArray)) != -1) {
System.out.write(buffArray, 0, i);
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Output : Enter WebSite Name :http://www.vasappanavara.org
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”
“http://www.w3.org/TR/html4/loose.dtd”>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html; charset=iso-8859-1”>
<title>Prof. Ramesh Vasappanavara</title>
<style type=”text/css”>
<!−
…………………………………………………
</body>
</html>
With URL class we could import the content of web site, but could not examine the content in detail before importing. URL connection is a class that allows us to examine the properties prior to transporting. Methods supported by URL connection are shown in Table 22.1.
Table 22.1 URLConnection class methods
URLConnection Class Methods | Functionality |
---|---|
int getContentLength() | Returns size in bytes else -1 |
long getDate() | Returns response time and date in milliseconds after Jan1 1970, of last modification |
long getExpiration() | Returns expiration time and date in milliseconds after Jan1 1970, of last modification |
long getLastModified() | Returns time and date in milliseconds after Jan1 1970, of last modification |
nputStream getInputStream() throws IOException | Returns InputStream of URL |
URLConnection: How to Set It to Work?
URL myurl = new URL(“http://www.vasappanavara.org”);
These concepts are shown in our next example.
Example 22.3: URLConnectionDemo.Java Write a Program to Show Usage of URLConnection Class Methods
//This program need Internet Connection
1. package com.oops.chap22;
2. import java.io.*;
3. import java.net.*;
4. import java.util.*;// for scanner class
5. public class URLConnectionDemo {
6. public static void main(String[] args)throws IOException {
7. String websitename; int ch;
8. Scanner scn=new Scanner(System.in);
9. System.out.print(“Enter WebSite Name :”);
10. websitename=scn.next();
11. try{
12. URL myurl = new URL(websitename);
13. URLConnection vrCon = myurl.openConnection();
14. // get date
15. long dt=vrCon.getDate();
16. System.out.println(“Date :”+ new Date(dt));
17. // get content length
18. int len=vrCon.getContentLength();
19. System.out.println(“ Size :” + len);
20. //get last modified date
21. dt=vrCon.getLastModified();
22. System.out.println(“Date lst modified:”+ new Date(dt));
23. //get the content
24. if ( len==0)System.out.println(“NoContent”);
25. else
26. { InputStream inputstream = vrCon.getInputStream();
27. while( ( ch = inputstream.read())!=-1)
28. System.out.print((char)ch);
29. inputstream.close();
30. }
31. }catch (Exception e) {e.printStackTrace();}
32. }
33. }
Output: Enter WebSite Name :http://www.vasappanavara.org
Date :Sun Dec 19 19:56:32 IST 2010
Size :16880
Date lst modified:Fri Oct 01 07:04:33 IST 2010
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN
……………………………………………………….
</body>
</html>
Line Nos. 12 & 13: | URL myurl = new URL(websitename); URLConnection vrCon = myurl.openConnection(); create an object of URL called myurl and uses openConnection() method of URLConnection class |
Line Nos. 15–21: | get information about URL such as date, content length , last modified date etc |
Line Nos. 26 & 27: | InputStream inputstream = vrCon.getInputStream(); while( ( ch = inputstream.read())! = -1) read the input stream and prints content of web site character by character |
You would have noticed power sockets. Insert a plug and power flows through the socket and runs your devices. Likewise, a socket in communications is connecting point between a server and a client so that a reliable bidirectional communication can go on between server and client.
Sockets have unique identification numbers also called port numbers and take 16 bits (2 bytes). In Section 22.2.1, we have already discussed port numbers that are reserved for standard applications such as http/ftp, etc. Note that whenever a new socket is created, a new port number must be allocated to the port.
There are two kinds of sockets: Server Side socket called ServerSocket, created using ServerSocket class, and client side socket called socket Created using a socket class. A ServerSocket can reside in any system that has service to offer. For example, a ServerSocket can be created on client if it has any services to offer.
ServerSocket, once created, listens either to local or remote clients and connects them on particular published ports. This is accomplished by ServerSocket first registering itself with the system. The constructors accept the port number and queue length, i.e., the maximum number of clients a server can accept. The constructors for ServerSocket are listed in Table 22.2. ServerSocket has a method called accept() that blocks the server and waits for client request for connection. A socket for the client is created by the server
Table 22.2 ServerSocket constructors
ServerSocket Class Constructors | Functionality |
---|---|
ServerSocket(int port) | ServerSocket on specified port with default queue length of 50 is created |
ServerSocket(int port,int len) | ServerSocket on specified port with queue length of len is created |
ServerSocket(int port,int len, InetAddress localaddress) | ServerSocket on specified port with queue length of len is created Belonging to local address system |
Socket class and by using accept() method
Socket clientskt = serverskt.accept();
used by clientskt to sent the data to client.
OutputStream comobj = clientskt. getOutputStream();
PrintStream prntobj =new PrintStream(comobj)
prntobj.println(stg);//stg is a message
Figure 22.4 Input from remote client
Socket skt = new Socket (“IPaddress”, port number);
IPAddress is the IP address of the server. To know IPAddress of a computer, goto contl panel lNetworkConnections ---> Local area connections ---> TCP/IP ----> you can see the IPAddress of a machine.
getInputStream() which returns an input stream object. This object will be used by skt object to receive data from the server. InputStream comobj = skt. getInputStream();
BufferedReader bfrtobj = new BufferedReader (new InputStreamReader(comobj));
Stg= bfrobj.readLine(); // stg is a message
Figure 22.5 Input from remoteserver
In this section, you will learn client server programming. As the heading suggests, there is a server which is running forever listening for clients on a published port. Obviously the server has a service to offer which is of interest to the client. There is a limit to the number of clients a server can accept; this limit is called max queue length of the server. The server uses ServerSocket class.
Then there is a client who knows the server's address and port number on which a particular application is running. Client sends a service request which will be accept() method by Server. Accept() method also returns a ServerSocket object.
After the connection is established, both server and client will establish stream connections and carry out communications. As a first example, we will establish connection and pass two string messages to client.
Example 22.4: SrverDemo1.Java A Java Program for Server Side Docket for Passing String Messages to Client
1. package com.oops.chap22;
2. import java.io.*;
3. import java.net.*;
4. public class SrverDemo1 {
5. public static void main(String[] args)throws IOException {
6. //server socket
7. ServerSocket servskt = new ServerSocket (8345);
8. //block the server i.e use accept()& create client socket at server
9. Socket clientskt = servskt.accept();
10. // Link OutputStream to socket object clientskt with getOutputStream()
11. OutputStream comobj = clientskt. getOutputStream();
12. //Use PrintStream to transport datas to socket : clientskt
13. PrintStream prntobj =new PrintStream( comobj);
14. String stg1 = “Welcome client”;
15. String stg2 = “ Networking program run a great fun!”;
16. //send data
17. prntobj.println(stg1);
18. prntobj.println(stg2);
19. //close all
20. servskt.close(); clientskt.close();
21. }
22. }
Line No. 7: | creates a ServerSocket object called sevskt. Line No. 9 creates an object of Socket class for client and makes ServerSocket call accept() method. |
Line No. 11: | attaches output stream to client socket OutputStream comobj = clientskt. getOutputStream(); |
Line No. 12: | creates a print stream for sending data to client PrintStream prntobj =new PrintStream( comobj); Line No. 17 & 18 send the String message to client |
Line Nos. 17 & 18: | send messages to client prntobj.println(stg1); |
Run the program form command prompt. Refer to Example 15.5 for necessary instructions. For simplicity and ease of execution, you can remove the package class from all the client server programs and compile and execute all in one directory, say
c:oopsjavaworkspaceoopstechsrccooopschap22
Exercise problems at the end of the chapter show the way.
Example 22.5: ClientDemo1.Java A Client Side Socket Program to Establish Connection with Server and Receive Messages from Server
1. package com.oops.chap22;
2. import java.io.*;
3. import java.net.*;
4. public class ClientDemo1 {
5. public static void main(String[] args)throws IOException {
6. //create a client socket using Socket class
7. Socket skt = new Socket ( “localhost” ,8345);
8. //Link IntputStream to socket object skt
9. InputStream comobj = skt. getInputStream();
10. //Use BufferedReader to get the data from socket
11. BufferedReader bfrtobj =new BufferedReader ( new InputStreamReader(comobj));
12. //Receive messages
13. String stg;
14. while(( stg=bfrtobj.readLine()) != null)
15. System.out.println(“
Message from Server” + stg);
16. //close all
17. skt.close(); bfrtobj.close();
18. }
19. }
Output: Message from Server :Welcome client
Message from Server Networking program run a great fun!
In this section, we will handle two-way communication between a server and a client. Server stores two arrays. In one array RollNumbers are stored and in the second array academic grades are stored. Client sends roll number and server checks for the grade and sends them to client. Client then displays the result. The concept is shown in Figure 22.6.
Figure 22.6 Client server two-way communications
Example 22.6a: Write Java Client Server Program Wherein Client Submits Roll Number and Gets Grade from Server–Server Side Programming
package com.oops.chap22;
import java.io.*;
import java.util.*;
import java.net.*;
public class ServerDemo2 {
public static void main(String[] args)throws IOException {
int id, index=0;String gr;
int []rolls = new int[]{50595,50596,50597,50598,50599};
String[] grade= new String[]{“A”,”C”,”B”,”C”,”A”};
try{
//server socket
ServerSocket servskt = new ServerSocket (5000);
//block the server i.e use accept()& create client socket at server
Socket clientskt = servskt.accept();
// Create a BufferedReaderStream to get the data from the client
BufferedReader bufrclient=new BufferedReader
( new InputStreamReader(clientskt.getInputStream()));
//create buffer writer stream for sending data to client
PrintWriter prwtr = new PrintWriter(clientskt.getOutputStream(),true);
//read from client and send the result. Server is in a for ever loop
while ( true)
{// read a line create a StringTokenizer
StringTokenizer stkn = new StringTokenizer(bufrclient.readLine());
//conver String to Integer
id= new Integer(stkn.nextToken()).intValue();
System.out.println(“
id received from the client” + id);
// find the index number from rolls array
for( int i=0;i<rolls.length;i++)
{ if( id==rolls[i])
index=i;}
// Get the grade*/
gr=grade[index];
// send grade to client
prwtr.println(gr);
// print on server console too
System.out.println(“Grade of “+ id + “ is :”+ gr);}
}catch(IOException e){}
}
}
Example 22.6b: Write Java Client Server Program Wherein Client Submits Roll Number and Gets Grade from Server–Client Side Programming
package com.oops.chap22;
import java.io.*;
import java.util.*;
import java.net.*;
public class ClientDemo2 {
public static void main(String[] args)throws IOException {
int id, index=0;String gr;
//socket to connect to server
Socket skt = new Socket(“localhost”,5000);
// Create a BufferedInputStream to get the data from the server
BufferedReader bufrserver=new BufferedReader
( new InputStreamReader(skt.getInputStream()));
//create buffer writer stream for sending data to server
PrintWriter prwtr = new PrintWriter(skt.getOutputStream(),true);
//continuously send roll number and get grade from the server.
while ( true)
{ Scanner scn= new Scanner(System.in);
System.out.println(“
Enter roll number< 50595 to 50599>”);
id = scn.nextInt();
// send id to server
prwtr.println(id);
// get grade from the server
StringTokenizer stkn =new StringTokenizer(bufrserver.readLine());
System.out.println(“Grade received from server of “+ id + “ is :”+ stkn.nextToken());
}
}
}
In real life, there will be several clients wishing to connect to server at the same tine. For example, when results are declared, several students rush in to connect to server. The best way to handle such a situation is to put each client on a separate thread. The server can achieve the result by
ServerSocket servskt = new ServerSocket (6000);
while( true) {
Socket clientskt = servskt.accept();
Thread thrd = new Thread(clientskt);}
Each loop will create a new connection on server socket. New thread handles the communication between Server and multiple client.
Our next example shows multiple clients being handled by thread. The user will send the server a number and the server returns Boolean true or false to indicate if the number of even or odd.
Example 22.8a: Write Java Client Server Program–Server to Handle Multiple Clients Using Thread–Server Side Programming
package com.oops.chap22;
import java.io.*;
import java.util.*;
import java.net.*;
public class MultipleClientServer {
public static void main(String[] args)throws IOException {
try {
//server socket
ServerSocket servskt = new ServerSocket (4000);
int count=0; // counting thread
while ( true)
{// listen for a request
Socket clientskt = servskt.accept();
System.out.println(“
Starting thread No “+count);
//create a new thread by calling the constructor of class CommThread
CommThread thrd = new CommThread(clientskt,count);
thrd.start();
}//end of while
}catch(IOException e){}
}//end of main
}//end of class
class CommThread extends Thread
{ private Socket clientskt ; // connected
private int count; // count for label the thread
CommThread(Socket s , int i){clientskt=s; count=i;}
public void run()
{ boolean evenodd=true;
try
{ // Create a BufferedReaderStream to get the data from the client BufferedReader bufrclient=new BufferedReader
( new InputStreamReader(clientskt.getInputStream()));
//create buffer writer stream for sending data to client
PrintWriter prwtr = new PrintWriter(clientskt.getOutputStream (),true);
// Serve in a continuous loop
while ( true)
{// receive the string data from client
StringTokenizer stkn = new StringTokenizer(bufrclient.readLine());
//get year
int num = new Integer(stkn.nextToken()).intValue();
System.out.println(“
Number Received From Client “+ num);
//check even or odd
if ( num%2!=0)evenodd=false;
else evenodd=true;
//send evenodd to client
prwtr.println(evenodd);
System.out.println(“
Number “+ num +” is :”+ evenodd);
}
}catch(IOException e ){}
}
Example 22.8b: Write Java Client Server Program for Client–Server to Handle Multiple Clients Using Thread–Client Side Programming
package com.oops.chap22;
import java.util.*;
import java.io.*;
import java.net.*;
public class MultipleclientsClient {
public static void main(String[] args)throws IOException {
//socket to connect to server
Socket skt = new Socket(“localhost”,4000);
// Create a BufferedInputStream to get the data from the server
BufferedReader bufrserver=new BufferedReader
( new InputStreamReader(skt.getInputStream()));
//create buffer writer stream for sending data to server
PrintWriter prwtr = new PrintWriter(skt.getOutputStream(),true);
//continuously send number and get grade from the server.
while ( true)
{ Scanner scn= new Scanner(System.in);
System.out.println(“
Enter number< 50595 to 50599>”);
int id = scn.nextInt();
// send id to server
prwtr.println(id);
// get even or odd from the server
StringTokenizer stkn =new StringTokenizer(bufrserver.readLine());
System.out.println(“EvenOdd received from server of “+ id + “ is :”+ stkn.nextToken());
}}}
Many a times we need to download a file located in a server. The solved Example 4a and 4b shows the technique to download file from a remote server. As usual at server, we need a server socket and a client-specific socket. Then we need BufferedReader to accept data from the client and DataOutputStreamReader to send the data to client.
3.21.246.223