22

Networking in Java

LEARNING OBJECTIVES

At the end of the chapter, you will be able to understand and use

  • TCP/IP protocols.
  • Inet addressing mechanism and URL connections.
  • TCP/IP sockets.
  • Client server applications.

22.1 Introduction

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.

22.2 Basics of Networking

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).

22.2.1 TCP/IP

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.

  • Connection oriented means the sender confirms if the receiver has indeed received the data or not. If not received, then the retransmission of data takes place.
  • TCP/IP is a point-to-point reliable communication, i.e., it is an acknowledged service that ensures correct reception of data at receiver. TCP/IP has five layers, as shown in Figure 22.3.
  • Java programs written come under Application Layer. Hyper Text Transfer Protocol (HTTP) and File Transfer Protocol (FTP) and Telnet are some of the widely used protocols at the application layer.
  • Application Layer receives the data from IO streams of sender and format data as streams of continuous bytes and sends them to Transport layer, as shown in Figure 22.1.

     

    TCP/UDP functionality

     

    Figure 22.1 TCP/UDP functionality

  • Transport Layer receives these streams of data through assigned ports and makes a packet (Figure 22.1). A packet will encompass Port Number and data.
  • Port numbers vary between 0 and 65535 and are represented by a 16-bit number. Note that these numbers are logical and have nothing to do with physical ports on computer systems. The port numbers ranging from 0 to 1,022 are restricted; they are reserved for use by well-known services such as HTTP and FTP and other system services. Examples of well-known ports are:
    • Domain Name System (DNS): 53
    • File Transfer Protocol (FTP): 21
    • Hypertext Transfer Protocol (HTTP): 80
    • Network News Transfer Protocol (NNTP):119
    • Post Office Protocol (POP3): 110
    • Simple Mail Transfer Protocol (SMTP): 25
    • Telnet: 22
  • IP Layer receives the packet and encapsulates the packet into envelops called frames (Figure 22.2). A frame will have source address, destination address, data, and some bits reserved for error detection and correction mechanism. For specifying the address, IP address is specified. An IP address is a 32-bit address which identifies computers connected to networks uniquely. For example, 192.167.169.24. This protocol is called IPV 4. A new protocol called IP V 6 has been introduced which follows 48-bit addressing mechanisms and the Internet allows both IPs.

     

    IP layer encapsulation of packet in a frame

     

    Figure 22.2 IP layer encapsulation of packet in a frame

     

    TCP/IP model layers

     

    Figure 22.3 TCP/IP model layers

     

  • Address of destination can be specified by numeric address like 192.127.68.24 or by domain name like www.google.com. The transformation is carried out by Domain name server which transforms address from numeric to web site name and vice versa.
  • Data Link Layer receives the Frame from IP layer and dispatch the frame to destination computer. This layer has device drivers and contains Media Access Control Protocol in Network Card. Network card maps the IP address into 48-bit unique Network card id number and transmits based on MAC protocol. MAC protocol simply tells which is going on the Net next, i.e., it tells the rules for sharing single transmission medium by multiple frames.
  • When the destination computer received the frames, the formats are decoded based on the protocol used and frames are handed over to the IP layer. The IP layer produces packets and hands it over to Transport Layer. The transport layer hands over data at specified ports, as shown in Figure 22.3.

22.2.2 User Data Gram Protocol (UDP)

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.

22.3 Internet Address

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)

22.4 URL and URL Connection

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 (String protocol, String host, int port, String file) throws MalformedURLException.
  • URL (String protocol, String host, String file) throws MalformedURLException.
  • URL (String urlString) throws MalformedURLException.

URL Methods

  • String getFile()
  • String getHost()
  • int getPort()
  • String getProtocol()

URL: How to Set It to Work?

  • Create URL object that represents resource on www address
  • URL myurl = new URL(“http://www.vasappanavara.org”);
  • Create an URL connection that can connect to concerned web site
  • InputStream inputstream = myurl.openStream();
  • Using StreamReader create a buffer, say of data type byte, for reading stream data from URL connection.

    byte buffArray[ ] = new byte[1024];

  • Use read() method of that URLConnection object and create InputStream for reading stream of data from the URL.
   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>

22.4.1 URL Connection

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?

  • Create URL object that represents resource on www address

    URL myurl = new URL(“http://www.vasappanavara.org”);

  • Create an URL connection that can connect to concerned web site.
  • Use getInputStream() method of that URLConnection object and create InputStream for reading stream of data from the URL.
  • Using input stream reader, create a BufferedReader object for reading stream data, i.e., characters from URL connection.

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

22.5 TCP/IP Sockets

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.

22.5.1 ServerSocket Class

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

22.5.2 Server and Socket for Communications: How to Set them to Work?

  • At server, create a server socket using ServerSocket class and allocate a port number: ServerSocket servskt = new ServerSocket (port number);
  • Make the server wait for client connection request by creating a client socket by using

    Socket class and by using accept() method

    Socket clientskt = serverskt.accept();

  • Link OutputStream to socket object clientskt just created by using getOutputStream() which returns a output stream object. This object will be

    used by clientskt to sent the data to client.

    OutputStream comobj = clientskt. getOutputStream();

  • Use PrintStream to transport data to socket: clientskt

    PrintStream prntobj =new PrintStream(comobj)

  • Use println or print method to send data

    prntobj.println(stg);//stg is a message

  • At the end of transmission close all sockets: servskt.close(); clientskt. close(); and prntobj.close(). Figure 22.4 shows interconnection of server & client & stream readers & buffers.

     

    Input from remote client

     

    Figure 22.4 Input from remote client

22.5.3 Client and Socket for Communications: How to Set them to Work?

  • At Client, create a client socket using Socket class and specify the IPaddress of the server and allocate a port number :

    Socket skt = new Socket (“IPaddress”, port number);

    IPAddress is the IP address of the server. To know IPAddress of a computer, goto contl panel image lNetworkConnections ---> Local area connections ---> TCP/IP ----> you can see the IPAddress of a machine.

  • Link IntputStream to socket object skt just created by using

    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();

  • Use BufferedReader to get the data from socket: skt

    BufferedReader bfrtobj = new BufferedReader (new InputStreamReader(comobj));

  • Use read() or readLine() method to read the data

    Stg= bfrobj.readLine(); // stg is a message

  • At the end of transmission close all sockets : skt.clos(); bfrobj.close();. Figure 22.5 shows the interconnection of server & client & stream readers & buffers.

     

    Input from remoteserver

     

    Figure 22.5 Input from remoteserver

22.6 Client Server Program

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!

22.6.1 Client Server Two-way Communication Program

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.

 

Client server two-way communications

 

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());
 }
 }
 }

 

image

 

image

22.6.2 Multiple Clients and Server Programs Using Multithreads

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());
}}}

 

image

 

image

22.6.3 Client Server Program for File Download from Server

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.

22.7 Summary

  1. Java.net is a package that supports networking programs and allows us to create unix-like sockets and implementation of TCP/IP sockets.
  2. By attaching those stream files with networking protocols, you can write to files on the Internet and retrieving data from files over the Internet as if you are writing files on to disk.
  3. Networking is the ability to connect to Internet from our stand-alone applications or Applets. Network is a collection of computers, either homogenous or heterogeneous.
  4. Internet is a collection or grouping together of networks. We can say that Internet is a network of networks, comprising of millions of computers. These computers communicate with each other using Internet protocols.
  5. World Wide Web (WWW) is a way of accessing information on the Internet. It uses HTTP to exchange data amongst communicating computers.
  6. Computers running on the Internet communicate with each other using either the Transmission Control Protocol (TCP) or the User Datagram Protocol (UDP).
  7. 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.
  8. TCP/IP, i.e., Transmission Control Protocol and Internet Protocol, are standard protocols to be used for transmission of data.
  9. TCP/IP is a connection-oriented and reliable service.
  10. Connection oriented means the sender confirms if the receiver has indeed received the data or not. If not received then retransmission of data takes place.
  11. TCP/IP is a point-to-point reliable communication, i.e., it is an acknowledged service that ensures correct reception of data at receiver.
  12. TCP/IP has five layers, viz., Application Layer, Transportation Layer, IP Layer, Data Link Layer and Physical Layer.
  13. Address of destination can be specified by numeric address like 192.127.68.24 or by domain name like www.google.com.
  14. Domain name server transforms address from numeric to web site name and vice versa.
  15. Data Link Layer receives the Frame from IP layer and dispatches the frame to destination computer.
  16. Network card maps the IP address into 48-bit unique Network card identification number and transmits based on MAC protocol.
  17. MAC protocol simply tells which is going on the Net next, i.e., it tells the rules for sharing single transmission medium by multiple frames.
  18. UDP is a connection-less service. This means that 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.
  19. We can obtain Internet address for any web site by using InetAddress class of java.net package. Inet class throws UnknownHostException.
  20. URL connection is a class that allows us to examine the properties prior to transporting.
  21. Socket has unique identification number also called port number and takes 16 bits (2 bytes).
  22. ServerSocket created using ServerSocket class and second is client side socket, called socket created using a socket class.

Exercise Questions

Objective Questions

  1. Networking classes are included in
    1. java.IO.*;
    2. java.net.*;
    3. java.util.*;
    4. java.lang.*;
  2. URL stands for
    1. Universal Resource Locator
    2. Unified Resource Locator
    3. Uniform Resource Locator
    4. Unique Resource Locator
  3. Which of the following classes contain IP Address?
    1. Inet class
    2. URL class
    3. URL Connection class
    4. Socket class
  4. Which of the following statements are true in respect of TCP/IP?
    1. Connection oriented means acknowledgement from receiver
    2. TCP/IP is a point-to-point service
    3. There is a separate network layer in TCP/IP
    4. TCP/IP is a reliable service means acknowledgement else retransmission
    1. i, ii and iv
    2. i, ii and iii
    3. ii, iii and iv
    4. i and iii
  5. Output of transport layer of TCP/IP is
    1. continuous stream of bytes
    2. frame
    3. packet
    4. MAC Frame
  6. Output of Application layer of TCP/IP is
    1. continuous stream of bytes
    2. frame
    3. packet
    4. MAC Frame
  7. Port Numbers are represented by
    1. 8 bits
    2. 16 bits
    3. 32 bits
    4. 48 bits
  8. Port Number for http protocol is
    1. 110
    2. 60
    3. 80
    4. 22
  9. Port Number for post office protocol (POP) & FTP are
    1. 25 and 119
    2. 53 and 80
    3. 110 and 25
    4. 110 and 21
  10. Output of IP layer of TCP/IP is
    1. continuous stream of bytes
    2. frame
    3. packet
    4. MAC Frame
  11. accept() method returns
    1. Client socket
    2. Server Socket
    3. Socket
    4. Datagram socket

    Short-answer Questions

  12. What is a socket?
  13. What is a port number?
  14. What is an IP Address?
  15. When IP Address is available what is the need of port address also?
  16. Explain the role of ServerSocket.
  17. Explain the role of socket class for client.
  18. Distinguish TCP/IP connection and UDP connection service.
  19. Explain how a server listens for a connection at a port.

    Long-answer Questions

  20. Explain the function of each layer of TCP/IP Layers.
  21. Explain the process of creation of ServerSocket and socket for client with suitable examples.
  22. Explain the steps involved in setting up client server networking.
  23. Explain the role of Stream Readers and Writers and Buffered Stream in networking programs.
  24. How are multiple clients handled by a single server?
  25. Explain how a line of text can be obtained from the server.
  26. Explain how primitive data can be exchanged between server and a client.

    Assignment Questions

  27. Write a client and server program wherein a student enters the roll number and server houses random file that holds student results. Obtain the result and display on the client console.
  28. Write a program for Tic Tac toe server and client. Tic tac game is the game you would have played at some time or the other. Hint: Assume two-dimensional matrix display at both server and client and use two-way communication model.

     

    image

     

  29. Rewrite Ex 1 for multiple client paradigm.
  30. Modify two-way chat program to handle conference mode wherein there are three peer systems and messages are displayed at all terminals as on broadcast.
  31. Modify the problem at 4 to cater to sending messages only to intended clients.
  32. Write a client server program wherein BufferedReader is used for reading in the data and PrintStream is used for sending data.

Solutions to Objective Questions

  1. b
  2. c
  3. a
  4. a
  5. c
  6. a
  7. b
  8. c
  9. d
  10. b
  11. a
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.21.246.223