Вы находитесь на странице: 1из 25

Spring 2013 Master of Computer Application (MCA) Semester 4 MC0078 Java Programming 4 Credits

(Book ID: B0831 & B0832)

1. What are the difference between an interface and an abstract class? Ans.
An abstract class is a class that leaves one or more method implementations unspecified by declaring one or more methods abstract. An abstract method has no body (i.e., no implementation). A subclass is required to override the abstract method and provide an implementation. Hence, an abstract class is incomplete and cannot be instantiated, but can be used as a base class. abstract public class abstract-base-class-name { // abstract class has at least one abstract method public abstract return-type abstract-method-name ( formal-params ); ... // other abstract methods, object methods, class methods } public class derived-class-name extends abstract-base-class-name { public return-type abstract-method-name (formal-params) { stmt-list; } ... // other method implementations } It would be an error to try to instantiate an object of an abstract type: abstract-class-name obj = new abstract-class-name(); // ERROR! That is, operator new is invalid when applied to an abstract class.

Dinesh (521138580)
An interface is a specification, or contract, for a set of methods that a class that implements the interface must conform to in terms of the type signature of the methods. The class that implements the interface provides an implementation for each method, just as with an abstract method in an abstract class. So, you can think of an interface as an abstract class with all abstract methods. The interface itself can have either public, package, private or protected access defined. All methods declared in an interface are implicitly abstract and implicitly public. It is not necessary, and in fact considered redundant to declare a method in an interface to be abstract. You can define data in an interface, but it is less common to do so. If there are data fields defined in an interface, then they are implicitly defined to be: public. static, and final In other words, any data defined in an interface are treated as public constants. Note that a class and an interface in the same package cannot share the same name. Methods declared in an interace cannot be declared final. Why? Interface declaration Interface names and class names in the same package must be distinct. public interface interface-name { // if any data are defined, they must be constants public static final type-name var-name = constant-expr; // one or more implicitly abstract and public methods return-type method-name ( formal-params ); }

When to use an Interface vs when to use an abstract class:

MC00078

Page 2

Dinesh (521138580)
Having reviewed their basic properties, there are two primary differences between interfaces and abstract classes: an abstract class can have a mix of abstract and non-abstract methods, so some default implementations can be defined in the abstract base class. An abstract class can also have static methods, static data, private and protected methods, etc. In other words, a class is a class, so it can contain features inherent to a class. The downside to an abstract base class, is that since their is only single inheritance in Java, you can only inherit from one class. an interface has a very restricted use, namely, to declare a set of public abstract method singatures that a subclass is required to implement. An interfaces defines a set of type constraints, in the form of type signatures, that impose a requirement on a subclass to implement the methods of the interface. Since you can inherit multiple interfaces, they are often a very useful mechanism to allow a class to have different behaviors in different situations of usage by implementing multiple interfaces. It is usually a good idea to implement an interface when you need to define methods that are to be explicitly overridden by some subclass. If you then want some of the methods implemented with default implementations that will be inherited by a subclass, then create an implementation class for the interface, and have other class inherit (extend) that class, or just use an abstract base class instead of an interface.

2. Describe Exception Handling in JAVA Ans


An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, including the following:

A user has entered invalid data. A file that needs to be opened cannot be found. A network connection has been lost in the middle of communications, or the JVM has run out of memory.

Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner. To understand how exception handling works in Java, you need to understand the three categories of exceptions:

Checked exceptions: A checked exception is an exception that is typically a user error or a problem that cannot be foreseen by the programmer. For example, if a file is to be opened, but the file cannot be found, an exception

MC00078

Page 3

Dinesh (521138580)
occurs. These exceptions cannot simply be ignored at the time of compilation. Runtime exceptions: A runtime exception is an exception that occurs that probably could have been avoided by the programmer. As opposed to checked exceptions, runtime exceptions are ignored at the time of compliation. Errors: These are not exceptions at all, but problems that arise beyond the control of the user or the programmer. Errors are typically ignored in your code because you can rarely do anything about an error. For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.

Exception Hierarchy: All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class. Errors are not normally trapped form the Java programs. These conditions normally happen in case of severe failures, which are not handled by the java programs. Errors are generated to indicate errors generated by the runtime environment. Example : JVM is out of Memory. Normally programs cannot recover from errors. The Exception class has two main subclasses : IOException class and RuntimeException Class.

Here is a list of most common checked and unchecked Java's Built-in Exceptions.

MC00078

Page 4

Dinesh (521138580)

Exceptions Methods:
Following is the list of important medthods available in the Throwable class. S N 1 2 3 4 Methods with Description public String getMessage() Returns a detailed message about the exception that has occurred. This message is initialized in the Throwable constructor. public Throwable getCause() Returns the cause of the exception as represented by a Throwable object. public String toString() Returns the name of the class concatenated with the result of getMessage() public void printStackTrace() Prints the result of toString() along with the stack trace to System.err, the error output stream. public StackTraceElement [] getStackTrace() Returns an array containing each element on the stack trace. The element at index 0 represents the top of the call stack, and the last element in the array represents the method at the bottom of the call stack. public Throwable fillInStackTrace() Fills the stack trace of this Throwable object with the current stack trace, adding to any previous information in the stack trace.

Catching Exceptions: A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following: try { //Protected code }catch(ExceptionName e1) { //Catch block } A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follows the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter.

MC00078

Page 5

Dinesh (521138580)
Example: The following is an array is declared with 2 elements. Then the code tries to access the 3rd element of the array which throws an exception. // File Name : ExcepTest.java import java.io.*; public class ExcepTest{ public static void main(String args[]){ try{ int a[] = new int[2]; System.out.println("Access element three :" + a[3]); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Exception thrown :" + e); } System.out.println("Out of the block"); } } This would produce following result: Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 Out of the block Multiple catch Blocks: A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following: try { //Protected code }catch(ExceptionType1 e1) { //Catch block }catch(ExceptionType2 e2) { //Catch block }catch(ExceptionType3 e3) { //Catch block } The previous statements demonstrate three catch blocks, but you can have any number of them after a single try. If an exception occurs in the protected code, the exception is thrown to the first catch block in the list. If the data type of the exception thrown matches ExceptionType1, it gets caught there. If not, the exception passes down to the second catch statement. This continues until the exception either is caught or falls through all catches, in which case the current

MC00078

Page 6

Dinesh (521138580)
method stops execution and the exception is thrown down to the previous method on the call stack. Example: Here is code segment showing how to use multiple try/catch statements. try { file = new FileInputStream(fileName); x = (byte) file.read(); }catch(IOException i) { i.printStackTrace(); return -1; }catch(FileNotFoundException f) //Not valid! { f.printStackTrace(); return -1; } The throws/throw Keywords: If a method does not handle a checked exception, the method must declare it using the throws keyword. The throws keyword appears at the end of a method's signature. You can throw an exception, either a newly instantiated one or an exception that you just caught, by using the throw keyword. Try to understand the different in throws and throw keywords. The following method declares that it throws a RemoteException: import java.io.*; public class className { public void deposit(double amount) throws RemoteException { // Method implementation throw new RemoteException(); } //Remainder of class definition } A method can declare that it throws more than one exception, in which case the exceptions are declared in a list separated by commas. For example, the following method declares that it throws a RemoteException and an InsufficientFundsException:

MC00078

Page 7

Dinesh (521138580)
import java.io.*; public class className { public void withdraw(double amount) throws RemoteException, InsufficientFundsException { // Method implementation } //Remainder of class definition } The finally Keyword The finally keyword is used to create a block of code that follows a try block. A finally block of code always executes, whether or not an exception has occurred. Using a finally block allows you to run any cleanup-type statements that you want to execute, no matter what happens in the protected code. A finally block appears at the end of the catch blocks and has the following syntax: try { //Protected code }catch(ExceptionType1 e1) { //Catch block }catch(ExceptionType2 e2) { //Catch block }catch(ExceptionType3 e3) { //Catch block }finally { //The finally block always executes. } Example: public class ExcepTest{ public static void main(String args[]){ int a[] = new int[2]; try{ System.out.println("Access element three :" + a[3]); }catch(ArrayIndexOutOfBoundsException e){ System.out.println("Exception thrown :" + e); } finally{ a[0] = 6;

MC00078

Page 8

Dinesh (521138580)
System.out.println("First element value: " +a[0]); System.out.println("The finally statement is executed"); } } } This would produce following result: Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 3 First element value: 6 The finally statement is executed Note the following:

A catch clause cannot exist without a try statement. It is not compulsory to have finally clauses when ever a try/catch block is present. The try block cannot be present without either catch clause or finally clause. Any code cannot be present in between the try, catch, finally blocks.

Declaring you own Exception: You can create your own exceptions in Java. Keep the following points in mind when writing your own exception classes:

All exceptions must be a child of Throwable. If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class. If you want to write a runtime exception, you need to extend the RuntimeException class.

We can define our own Exception class as below: class MyException extends Exception{ } You just need to extend the Exception class to create your own Exception class. These are considered to be checked exceptions. The following InsufficientFundsException class is a user-defined exception that extends the Exception class, making it a checked exception. An exception class is like any other class, containing useful fields and methods. Example: // File Name InsufficientFundsException.java import java.io.*;

MC00078

Page 9

Dinesh (521138580)

public class InsufficientFundsException extends Exception { private double amount; public InsufficientFundsException(double amount) { this.amount = amount; } public double getAmount() { return amount; } } To demonstrate using our user-defined exception, the following CheckingAccount class contains a withdraw() method that throws an InsufficientFundsException. // File Name CheckingAccount.java import java.io.*; public class CheckingAccount { private double balance; private int number; public CheckingAccount(int number) { this.number = number; } public void deposit(double amount) { balance += amount; } public void withdraw(double amount) throws InsufficientFundsException { if(amount <= balance) { balance -= amount; } else { double needs = amount - balance; throw new InsufficientFundsException(needs); } } public double getBalance() { return balance; } public int getNumber()

MC00078

Page 10

Dinesh (521138580)
{ return number; } } The following BankDemo program demonstrates invoking the deposit() and withdraw() methods of CheckingAccount. // File Name BankDemo.java public class BankDemo { public static void main(String [] args) { CheckingAccount c = new CheckingAccount(101); System.out.println("Depositing $500..."); c.deposit(500.00); try { System.out.println("\nWithdrawing $100..."); c.withdraw(100.00); System.out.println("\nWithdrawing $600..."); c.withdraw(600.00); }catch(InsufficientFundsException e) { System.out.println("Sorry, but you are short $" + e.getAmount()); e.printStackTrace(); } } } Compile all the above three files and run BankDemo, this would produce following result: Depositing $500... Withdrawing $100... Withdrawing $600... Sorry, but you are short $200.0 InsufficientFundsException at CheckingAccount.withdraw(CheckingAccount.java:25) at BankDemo.main(BankDemo.java:13) Common Exceptions: In java it is possible to define two catergories of Exceptions and Errors.

MC00078

Page 11

Dinesh (521138580)

JVM Exceptions: - These are exceptions/errors that are exclusively or logically thrown by the JVM. Examples : NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException, Programmatic exceptions . These exceptions are thrown explicitly by the application or the API programmers Examples: IllegalArgumentException, IllegalStateException.

2. Describe the following with respect to implementation of Sockets in Java: a. Reading from and Writing to a Socket b. Writing the Server Side of a Socket Ans: (a) Reading from and Writing to a Socket
The following program is a simple example of how to establish a connection from a client program to a server program through the use of sockets. The Socket class in the java.net package is a platform-independent implementation of the client end of a two-way communication link between a client and a server. The Socket class sits on top of a platform-dependent implementation, hiding the details of any particular system from your Java program. By using the java.net Socket class instead of relying on native code, your Java programs can communicate over the network in a platform-independent fashion. This client program, EchoTest, connects to the standard Echo server (on port 7) via a socket. The client both reads from and writes to the socket. EchoTest sends all text typed into its standard input to the Echo server by writing the text to the socket. The server echos all input it receives from the client back through the socket to the client. The client program reads and displays the data passed back to it from the server: import java.io.*; import java.net.*; public class EchoTest { public static void main(String[] args) { Socket echoSocket = null; DataOutputStream os = null; DataInputStream is = null; DataInputStream stdIn = new DataInputStream(System.in); try { echoSocket = new Socket("taranis", 7); os = new DataOutputStream(echoSocket.getOutputStream()); is = new DataInputStream(echoSocket.getInputStream()); } catch (UnknownHostException e) { System.err.println("Don't know about host: taranis");

MC00078

Page 12

Dinesh (521138580)
} catch (IOException e) { System.err.println("Couldn't get I/O for the connection to: taranis"); } if (echoSocket != null && os != null && is != null) { try { String userInput; while ((userInput = stdIn.readLine()) != null) { os.writeBytes(userInput); os.writeByte('\n'); System.out.println("echo: " + is.readLine()); } os.close(); is.close(); echoSocket.close(); } catch (IOException e) { System.err.println("I/O failed on the connection to: taranis"); } } } } Let's walk through the program and investigate the interesting bits. The following three lines of code within the first try block of the main() method are critical--they establish the socket connection between the client and the server and open an input stream and an output stream on the socket: echoSocket = new Socket("taranis", 7); os = new DataOutputStream(echoSocket.getOutputStream()); is = new DataInputStream(echoSocket.getInputStream()); The first line in this sequence creates a new Socket object and names it echoSocket. The Socket constructor used here (there are three others) requires the name of the machine and the port number that you want to connect to. The example program uses the hostname taranis, which is the name of a (hypothetical) machine on our local network. When you type in and run this program on your machine, you should change this to the name of a machine on your network. Make sure that the name you use is the fully qualified IP name of the machine that you want to connect to. The second argument is the port number. Port number 7 is the port that the Echo server listens to. The second line in the code snippet above opens an output stream on the socket, and the third line opens an input stream on the socket. EchoTest merely needs to write to the output stream and read from the input stream to communicate through the socket to the server. The rest of the program achieves this. If you are not yet familiar with input and output streams, you may wish to read Input and Output Streams .

MC00078

Page 13

Dinesh (521138580)
The next section of code reads from EchoTest's standard input stream (where the user can type data) a line at a time. EchoTest immediately writes the input text followed by a newline character to the output stream connected to the socket. String userInput; while ((userInput = stdIn.readLine()) != null) { os.writeBytes(userInput); os.writeByte('\n'); System.out.println("echo: " + is.readLine()); } The last line in the while loop reads a line of information from the input stream connected to the socket. The readLine() method blocks until the server echos the information back to EchoTest. When readline() returns, EchoTest prints the information to the standard output. This loop continues--EchoTest reads input from the user, sends it to the Echo server, gets a response from the server and displays it--until the user types an end-of-input character. When the user types an end-of-input character, the while loop terminates and the program continues, executing the next three lines of code: os.close(); is.close(); echoSocket.close(); These lines of code fall into the category of housekeeping. A well-behaved program always cleans up after itself, and this program is well-behaved. These three lines of code close the input and output streams connected to the socket, and close the socket connection to the server. The order here is important--you should close any streams connected to a socket before you close the socket itself. This client program is straightforward and simple because the Echo server implements a simple protocol. The client sends text to the server, the server echos it back. When your client programs are talking to a more complicated server such as an http server, your client program will also be more complicated. However, the basics are much the same as they are in this program: 1. 2. 3. 4. 5. Open a socket. Open an input stream and output stream to the socket. Read from and write to the stream according to the server's protocol. Close streams. Close sockets.

Only step 3 differs from client to client, depending on the server. The other steps remain largely the same.

(b). Writing the Server Side of a Socket

MC00078

Page 14

Dinesh (521138580)
This section shows you how to write a server and the client that goes with it. The server in the client/server pair serves up Knock Knock jokes. Knock Knock jokes are favored by children and are usually vehicles for bad puns. They go like this: Server: "Knock knock!" Client: "Who's there?" Server: "Dexter." Client: "Dexter who?" Server: "Dexter halls with boughs of holly." Client: "Groan." The example consists of two independently running Java programs: the client program and the server program. The client program is implemented by a single class, KnockKnockClient, and is very similar to the EchoClient example from the previous section. The server program is implemented by two classes: KnockKnockServer and KnockKnockProtocol, KnockKnockServer contains the main method for the server program and performs the work of listening to the port, establishing connections, and reading from and writing to the socket. KnockKnockProtocol serves up the jokes. It keeps track of the current joke, the current state (sent knock knock, sent clue, and so on), and returns the various text pieces of the joke depending on the current state. This object implements the protocol-the language that the client and server have agreed to use to communicate. The following section looks in detail at each class in both the client and the server and then shows you how to run them. The Knock Knock Server This section walks through the code that implements the Knock Knock server program. Here is the complete source for the KnockKnockServer class. The server program begins by creating a new ServerSocket object to listen on a specific port (see the statement in bold in the following code segment). When writing a server, choose a port that is not already dedicated to some other service. KnockKnockServer listens on port 4444 because 4 happens to be my favorite number and port 4444 is not being used for anything else in my environment: try { serverSocket = new ServerSocket(4444); } catch (IOException e) { System.out.println("Could not listen on port: 4444"); System.exit(-1); } ServerSocket is a java.net class that provides a system-independent implementation of the server side of a client/server socket connection. The constructor for ServerSocket throws an exception if it can't listen on the specified

MC00078

Page 15

Dinesh (521138580)
port (for example, the port is already being used). In this case, the KnockKnockServer has no choice but to exit. If the server successfully binds to its port, then the ServerSocket object is successfully created and the server continues to the next step--accepting a connection from a client (shown in bold): Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.out.println("Accept failed: 4444"); System.exit(-1); } The accept method waits until a client starts up and requests a connection on the host and port of this server (in this example, the server is running on the hypothetical machine taranis on port 4444). When a connection is requested and successfully established, the accept method returns a new Socket object which is bound to the same local port and has its remote address and remote port set to that of the client. The server can communicate with the client over this new Socket and continue to listen for client connection requests on the original ServerSocket This particular version of the program doesn't listen for more client connection requests. However, a modified version of the program is provided in Supporting Multiple Clients. After the server successfully establishes a connection with a client, it communicates with the client using this code: PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String inputLine, outputLine; // initiate conversation with client KnockKnockProtocol kkp = new KnockKnockProtocol(); outputLine = kkp.processInput(null); out.println(outputLine); while ((inputLine = in.readLine()) != null) { outputLine = kkp.processInput(inputLine); out.println(outputLine); if (outputLine.equals("Bye.")) break; } This code:

MC00078

Page 16

Dinesh (521138580)
1. Gets the socket's input and output stream and opens readers and writers on them. 2. Initiates communication with the client by writing to the socket (shown in bold). 3. Communicates with the client by reading from and writing to the socket (the while loop). Step 1 is already familiar. Step 2 is shown in bold and is worth a few comments. The bold statements in the code segment above initiate the conversation with the client. The code creates a KnockKnockProtocol object-the object that keeps track of the current joke, the current state within the joke, and so on. After the KnockKnockProtocol is created, the code calls KnockKnockProtocol's processInput method to get the first message that the server sends to the client. For this example, the first thing that the server says is "Knock! Knock!" Next, the server writes the information to the PrintWriter connected to the client socket, thereby sending the message to the client. Step 3 is encoded in the while loop. As long as the client and server still have something to say to each other, the server reads from and writes to the socket, sending messages back and forth between the client and the server. The server initiated the conversation with a "Knock! Knock!" so afterwards the server must wait for the client to say "Who's there?" As a result, the while loop iterates on a read from the input stream. The readLine method waits until the client responds by writing something to its output stream (the server's input stream). When the client responds, the server passes the client's response to the KnockKnockProtocol object and asks the KnockKnockProtocol object for a suitable reply. The server immediately sends the reply to the client via the output stream connected to the socket, using a call to println. If the server's response generated from the KnockKnockServer object is "Bye." this indicates that the client doesn't want any more jokes and the loop quits. The KnockKnockServer class is a well-behaved server, so the last several lines of this section of KnockKnockServer clean up by closing all of the input and output streams, the client socket, and the server socket: out.close(); in.close(); clientSocket.close(); serverSocket.close(); The Knock Knock Protocol The KnockKnockProtocol class implements the protocol that the client and server use to communicate. This class keeps track of where the client and the server are in their conversation and serves up the server's response to the client's statements. The KnockKnockServer object contains the text of all the jokes and makes sure that the client gives the proper response to the server's statements. It

MC00078

Page 17

Dinesh (521138580)
wouldn't do to have the client say "Dexter who?" when the server says "Knock! Knock!" All client/server pairs must have some protocol by which they speak to each other; otherwise, the data that passes back and forth would be meaningless. The protocol that your own clients and servers use depends entirely on the communication required by them to accomplish the task. The Knock Knock Client The KnockKnockClient class implements the client program that speaks to the KnockKnockServer. KnockKnockClient is based on the EchoClient program in the previous section, Reading from and Writing to a Socket and should be somewhat familiar to you. But we'll go over the program anyway and look at what's happening in the client in the context of what's going on in the server. When you start the client program, the server should already be running and listening to the port, waiting for a client to request a connection. So, the first thing the client program does is to open a socket that is connected to the server running on the hostname and port specified: kkSocket = new Socket("taranis", 4444); out = new PrintWriter(kkSocket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream())); When creating its socket, KnockKnockClient uses the host name taranis, the name of a hypothetical machine on our network. When you type in and run this program, change the host name to the name of a machine on your network. This is the machine on which you will run the KnockKnockServer. The KnockKnockClient program also specifies the port number 4444 when creating its socket. This is a remote port number--the number of a port on the server machine--and is the port to which KnockKnockServer is listening. The client's socket is bound to any available local port--a port on the client machine. Remember that the server gets a new socket as well. That socket is bound to local port number 4444 on its machine. The server's socket and the client's socket are connected. Next comes the while loop that implements the communication between the client and the server. The server speaks first, so the client must listen first. The client does this by reading from the input stream attached to the socket. If the server does speak, it says "Bye." and the client exits the loop. Otherwise, the client displays the text to the standard output and then reads the response from the user, who types into the standard input. After the user types a carriage return, the client sends the text to the server through the output stream attached to the socket. while ((fromServer = in.readLine()) != null) { System.out.println("Server: " + fromServer);

MC00078

Page 18

Dinesh (521138580)
if (fromServer.equals("Bye.")) break; fromUser = stdIn.readLine(); if (fromUser != null) { System.out.println("Client: " + fromUser); out.println(fromUser); } } The communication ends when the server asks if the client wishes to hear another joke, the client says no, and the server says "Bye." In the interest of good housekeeping, the client closes its input and output streams and the socket: out.close(); in.close(); stdIn.close(); kkSocket.close(); Running the Programs You must start the server program first. To do this, run the server program using the Java interpreter, just as you would any other Java application. Remember to run the server on the machine that the client program specifies when it creates the socket. Next, run the client program. Note that you can run the client on any machine on your network; it does not have to run on the same machine as the server. If you are too quick, you might start the client before the server has a chance to initialize itself and begin listening on the port. If this happens, you will see a stack trace from the client. If this happens, just restart the client. If you forget to change the host name in the source code for the KnockKnockClient program, you will see the following error message: Don't know about host: taranis To fix this, modify the KnockKnockClient program and provide a valid host name for your network. Recompile the client program and try again. If you try to start a second client while the first client is connected to the server, the second client just hangs. The next section, Supporting Multiple Clients, talks about supporting multiple clients. When you successfully get a connection between the client and server, you will see the following text displayed on your screen:

MC00078

Page 19

Dinesh (521138580)
Server: Knock! Knock! Now, you must respond with: Who's there? The client echoes what you type and sends the text to the server. The server responds with the first line of one of the many Knock Knock jokes in its repertoire. Now your screen should contain this (the text you typed is in bold): Server: Knock! Knock! Who's there? Client: Who's there? Server: Turnip Now, you respond with: Turnip who?" Again, the client echoes what you type and sends the text to the server. The server responds with the punch line. Now your screen should contain this: Server: Knock! Knock! Who's there? Client: Who's there? Server: Turnip Turnip who? Client: Turnip who? Server: Turnip the heat, it's cold in here! Want another? (y/n) If you want to hear another joke, type y; if not, type n. If you type y, the server begins again with "Knock! Knock!" If you type n, the server says "Bye." thus causing both the client and the server to exit. If at any point you make a typing mistake, the KnockKnockServer object catches it and the server responds with a message similar to this: Server: You're supposed to say "Who's there?"! The server then starts the joke over again: Server: Try again. Knock! Knock! Note that the KnockKnockProtocol object is particular about spelling and punctuation but not about capitalization.

MC00078

Page 20

Dinesh (521138580)
Supporting Multiple Clients To keep the KnockKnockServer example simple, we designed it to listen for and handle a single connection request. However, multiple client requests can come into the same port and, consequently, into the same ServerSocket. Client connection requests are queued at the port, so the server must accept the connections sequentially. However, the server can service them simultaneously through the use of threads - one thread per each client connection. The basic flow of logic in such a server is this: while (true) { accept a connection; create a thread to deal with the client; } The thread reads from and writes to the client connection as necessary.

4. Define RMI. Define the architecture of RMI invocation. Ans.


Introduction to Distributed Computing with RMI: Remote Method Invocation (RMI) technology, first introduced in JDK 1.1, elevates network programming to a higher plane. Although RMI is relatively easy to use, it is a remarkably powerful technology and exposes the average Java developer to an entirely new paradigm--the world of distributed object computing. This course provides you with an in-depth introduction to this versatile technology. RMI has evolved considerably since JDK 1.1, and has been significantly upgraded under the Java 2 SDK. Where applicable, the differences between the two releases will be indicated. The design goal for the RMI architecture was to create a Java distributed object model that integrates naturally into the Java programming language and the local object model. RMI architects have succeeded; creating a system that extends the safety and robustness of the Java architecture to the distributed computing world. Interfaces: The Heart of RMI The RMI architecture is based on one important principle: the definition of behavior and the implementation of that behavior are separate concepts. RMI allows the code that defines the behavior and the code that implements the behavior to remain separate and to run on separate JVMs. This fits nicely with the needs of a distributed system where clients are concerned about the definition of a service and servers are focused on providing the service.

MC00078

Page 21

Dinesh (521138580)
Specifically, in RMI, the definition of a remote service is coded using a Java interface. The implementation of the remote service is coded in a class. Therefore, the key to understanding RMI is to remember that interfaces define behavior and classes define implementation. Remember that a Java interface does not contain executable code. RMI supports two classes that implement the same interface. The first class is the implementation of the behavior, and it runs on the server. The second class acts as a proxy for the remote service and it runs on the client. A client program makes method calls on the proxy object, RMI sends the request to the remote JVM, and forwards it to the implementation. Any return values provided by the implementation are sent back to the proxy and then to the client's program. RMI Architecture Layers: With an understanding of the high-level RMI architecture, take a look under the covers to see its implementation. The RMI implementation is essentially built from three abstraction layers. The first is the Stub and Skeleton layer, which lies just beneath the view of the developer. This layer intercepts method calls made by the client to the interface reference variable and redirects these calls to a remote RMI service. The next layer is the Remote Reference Layer. This layer understands how to interpret and manage references made from clients to the remote service objects. In JDK 1.1, this layer connects clients to remote service objects that are running and exported on a server. The connection is a one-to-one (unicast) link. In the Java 2 SDK, this layer was enhanced to support the activation of dormant remote service objects via Remote Object Activation. The transport layer is based on TCP/IP connections between machines in a network. It provides basic connectivity, as well as some firewall penetration strategies. By using a layered architecture each of the layers could be enhanced or replaced without affecting the rest of the system. For example, the transport layer could be replaced by a UDP/IP layer without affecting the upper layers. Stub and Skeleton Layer: The stub and skeleton layer of RMI lie just beneath the view of the Java developer. In this layer, RMI uses the Proxy design pattern as described in the book, Design Patterns by Gamma, Helm, Johnson and Vlissides. In the Proxy pattern, an object in one context is represented by another (the proxy) in a separate context. The proxy knows how to forward method calls between the participating objects. The following class diagram illustrates the Proxy pattern. Remote Reference Layer

MC00078

Page 22

Dinesh (521138580)
The Remote Reference Layers defines and supports the invocation semantics of the RMI connection. This layer provides a RemoteRef object that represents the link to the remote service implementation object. The stub objects use the invoke() method in RemoteRef to forward the method call. The RemoteRef object understands the invocation semantics for remote services. The JDK 1.1 implementation of RMI provides only one way for clients to connect to remote service implementations: a unicast, point-to-point connection. Before a client can use a remote service, the remote service must be instantiated on the server and exported to the RMI system. (If it is the primary service, it must also be named and registered in the RMI Registry). The Java 2 SDK implementation of RMI adds a new semantic for the client-server connection. In this version, RMI supports activatable remote objects. When a method call is made to the proxy for an activatable object, RMI determines if the remote service implementation object is dormant. If it is dormant, RMI will instantiate the object and restore its state from a disk file. Once an activatable object is in memory, it behaves just like JDK 1.1 remote service implementation objects. Other types of connection semantics are possible. For example, with multicast, a single proxy could send a method request to multiple implementations simultaneously and accept the first reply (this improves response time and possibly improves availability). In the future, Sun may add additional invocation semantics to RMI. Transport Layer: The Transport Layer makes the connection between JVMs. All connections are stream-based network connections that use TCP/IP. Even if two JVMs are running on the same physical computer, they connect through their host computer's TCP/IP network protocol stack. (This is why you must have an operational TCP/IP configuration on your computer to run the Exercises in this course). The following diagram shows the unfettered use of TCP/IP connections between JVMs.

5. (a) Write Java program to print the address of the study center.

Ans.
public class Address { System.out.println(" The Address of Study Center is A-135, Model town") }

MC00078

Page 23

Dinesh (521138580) 5. (b) Write a Java program to find the sum of 1+3+5+. for 10 terms in the series. Ans: class ExOnSumOfOddNumbers { public static void main(String ar[]) { int i; int sum=0; for(i=0;i<=20;i++) { if(i%2!=0) sum+=i; } System.out.println("sum of 1+3+5+upto 10 Numbers is:"+sum); } } OUTPUT sum of 1+3+5+upto 10 Numbers is:100 6. Write a program to copy one file to another file. Ans:
public class Main { public static void main(String[] args) throws Exception { BufferedWriter out1 = new BufferedWriter (new FileWriter("srcfile")); out1.write("string to be copied\n"); out1.close(); InputStream in = new FileInputStream (new File("srcfile")); OutputStream out = new FileOutputStream (new File("destnfile")); byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } in.close(); out.close(); BufferedReader in1 = new BufferedReader (new FileReader("destnfile")); String str; while ((str = in1.readLine()) != null) { System.out.println(str); } in.close(); } }

MC00078

Page 24

Dinesh (521138580)

MC00078

Page 25

Вам также может понравиться