Sunteți pe pagina 1din 30

Department of Computer Science & Engineering

LAB MANUAL

Session 2013-2014

Subject Name : - Distributed System Lab

Subject Code : - CS-752

Branch : - CSE/IT

Year : - 4th

Semester : - 7th

INTEGRAL UNIVERSITY LUCKNOW


Dsauli, Kursi Road, PO Basha-226026

Dept of CSE, IU, LKO ICS-453


INDEX

Week 1 Experiment No. Name of the Experiments Page No.

Objective Design and implementation of Java API.


1 A Program to import inbuilt packages of Java API Family and
demonstrate its different aspects of Software development
Strategies.

Week-2 Objective Creation and importing customized Java Packages

2 A Program to create a customized Package in Java and import


it in some other Java Program. Details of which is under
mentioned

Week-3 Objective Understanding Creation of an Applet using Swings

3 A Program to create an Applet demonstrating various drawing


methods of Applet and demonstrate event handling mechanism

Week-4 Objective Introducing Socket Programming

4 A Program to demonstrate the use of InetAddress,


UserDatagramSocket, UserDatagramPacket classes and
interfaces

Week-5 Objective Understanding the concept of Remote Methods Invocations

5 A Program to implement RMI in Java

Week-6 Objective Introduction of Multicast socket Programming in


Java Application

6 A Program to implement MulticastSocket Program in Java

Week-7 Objective Introduction OF TSR

7 A Program to implement TSR Programming


Week-8 Objective Understanding Concept of Prototype for Stateless file
server and its cache mechanism
8 A program to implement prototype for Stateless file server and
its cache mechanism

Dept of CSE, IU, LKO 2 ICS-453


Dept of CSE, IU, LKO 3 ICS-453
1. Book(s) & References
1.1. Herbert Schildt, “THE COMPLETE REFRENCE:JAVA”, TMTT
1.1.1. http://www.sahyadri.edu.in/SMCA/students_guide/3semnotes/java/Java%20The%20Co
mplete%20Reference,%207th%20Edition.pdf
1.2. Thinking In JAVA By Bruce Eckel
1.2.1. http://dspace.cusat.ac.in/jspui/bitstream/123456789/119/1/TIJ3.pdf, http://is2ifa-
01.univ-lyon1.fr/~denis/docs_MAIMSITNM2/TIJ/TIJ3_small_4p.pdf
1.3. Core java vol. 1,2 By Cay Horstmann; Gary Cornell
1.3.1. http://www.dcc.ufrj.br/~comp2/TextosJava/CJ1.pdf
1.4. Sun Certified Programmer for Java 5 by Kathy Sierra
1.4.1. https://java.net/downloads/jfjug/SCJP%20Sun%20Certified%20Programmer%20for
%20Java%206-0071591060.pdf
1.5. Programmer’s Guide to Java SCJP certification by Khalid Mughal
1.5.1. http://edu.ercess.co.in/ebooks/java/A-Programmer-Guide-to-Java-SCJP-
Certification.pdf
1.6. The JAVA® language Specification document by James Gostling from
“http://docs.oracle.com/javase/specs/jls/se7/jls7.pdf”

Web References for more Java Books “http://www.javalobby.org/articles/5books/full.jsp”

1.7. Relevant tools and IDEs for Java to be download from


1.7.1. http://www.oracle.com/technetwork/java/javase/downloads/jre7-downloads-
1880261.html
1.7.2. https://netbeans.org/downloads
1.7.3. http://www.oracle.com/technetwork/developer-tools/jdev/overview/index.html
1.7.4. http://www.myeclipseide.com/index.php?name=Recommend_Us&req=Download&versi
on=ME4S

Dept of CSE, IU, LKO 4 ICS-453


Week # 1 Design and implementation of Java API.

An application programming interface (API), in the context of Java, is a collection of prewritten


packages, classes, and interfaces with their respective methods, fields and constructors. Similar to a
user interface, which facilitates interaction between humans and computers, an API serves as a
software program interface facilitating interaction.

In Java, most basic programming tasks are performed by the API’s classes and packages, which are
helpful in minimizing the number of lines written within pieces of code.
Java Development Kit (JDK) is comprised of three basic components, as follows:

Java compiler
Java Virtual Machine (JVM)
Java Application Programming Interface (API)
The Java API, included with the JDK, describes the function of each of its components. In Java
programming, many of these components are pre-created and commonly used. Thus, the
programmer is able to apply prewritten code via the Java API. After referring to the available API
classes and packages, the programmer easily invokes the necessary code classes and packages for
implementation.
The API is a library of available Java classes, packages and interfaces. The three API types are as
follows:
Official Java core API, which is bundled with the JDK download.
Optional official Java APIs, which may be downloaded if needed.
Unofficial APIs, which are third-party APIs that may be downloaded from source websites.
The API help programmers determine class or package functions, parameters and other necessary
information. The official API includes packages, e.g., applet packages, graphics and GUI swing
There are 3 types of Java Programming Language Application Programming Interfaces (APIs)

the official core Java API, contained in the JDK or JRE, of one of the editions of the Java Platform.
The three editions of the Java Platform are Java ME (Micro edition), Java SE (Standard edition),
and Java EE (Enterprise edition).
optional official APIs that can be downloaded separately. The specification of these APIs are
defined according to a Java Specification Request (JSR), and sometimes some of these APIs are
later included in the core APIs of the platform (the most notable example of this kind is Swing).
unofficial APIs, developed by third parties, but not related to any JSRs.
Third parties can freely implement any JSR specifications for an official API (even for the core API
of the language), providing that they conform to the Technology Compatibility Kit (TCK) for this
JSR (the TCK is a suite of tests that checks conformance of implementations for a JSR). The result
of this freedom is that many official APIs have more implementations than the Sun's Reference
implementation (RI).

Dept of CSE, IU, LKO 5 ICS-453


Experiment # 1

Problem Statement:- A Program to import inbuilt packages of Java API


Family and demonstrate its different aspects of Software development
Strategies.

1 Objective
 To Learn Basic programming style in Java Programming
Development Environment.
 To gain ability to write, compile, debug and execute Java Program.
 Learning how to interface you with inbuilt Java Packages.
 Ready to work with different Java SE APIs.

2 After completing this experiment you will be able to:

 To use basic syntax structure of inbuilt Java Packages.


 Ready for start advanced coding in Java Programming Development.
 Know how to write, compile, debug and execute different classes of Java
Packages.

3 Required Tools / Apparatus: Unix/Linux Operating System, Bash Shell,


OpenJDK and JRE installed on Machines

4 Solution

Step 1 Open Any Text Editor and write code as given below:

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class EventApplet extends Applet implements ActionListener{
Button b;
TextField tf;
public void init(){
tf=new TextField();
tf.setBounds(30,40,150,20);
b=new Button("Click");
b.setBounds(80,150,60,50);
add(b);add(tf);
b.addActionListener(this);

Dept of CSE, IU, LKO 6 ICS-453


setLayout(null);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to graphical world of Java !!!");
}
}

Step 2 Then save, compile and run your code.


5 Exercise:
Q1. Write a program to display all the possible words from a supplied word?

Q2. Write a program to create an Applet and embed it on a web page ?

Q3. How to do solve Tower of Hanoi using graphical Mode for only 3 or 4 disks.

6 For Further Reading Student May Refer to the following Books

1 Herbert Schildt, “THE COMPLETE REFRENCE:JAVA”, TMTT (Available in Departmental and


Central Library at University campus)

2 Core java vol. 1,2 By Cay Horstmann; Gary Cornell (Available in Departmental and Central Library
at University campus)

Dept of CSE, IU, LKO 7 ICS-453


Week #2 Creation and importing customized Java Packages
Java is a friendly language and permits to create our own packages and use in programming. We know
earlier, Java allows us to create our exceptions. Creating packages are indispensable in project development
where number of developers are involved doing different modules and tasks. We know packages avoid name
collision problems. Package naming conventions are very helpful to locate the applications developed by a
single individual or team.
Following steps are to be followed in creating and using packages.
Create a package with a .class file
set the classpath from the directory from which you would like to access. It may be in a different drive and
directory. Let us call it as a target directory.
Write a program and use the file from the package.
Let us create a package called forest and place a class called Elephant in it. Access the package from a
different drive and directory.
1st Step: Create a package (forest) and place Elephant.class in it.
Let us assume C:\Knrp is the current directory where we would like to create the package.
C:\Knrp > notepad Elephant.java
package forest;
import java.util.*;
public class Elephant
{
public void getDetails(String nickName, int weight)
{
System.out.println("Elephant nick name is " + nickName);
System.out.println("Elephant weight is " + weight);
}
}
Order of Package Statement
The above program codingwise is very simple but is important to know the steps of package creation.
package forest;
import java.util.*;
public class Elephant
package is a keyword of Java followed by the package name. Just writing the package statement followed by
the name creates a new package; see how simple Java is to practice. For this reason, Java is known as a
production language.

While creating packages, the order of statements is very important. The order must be like this, else,
compilation error.
Package statement

Dept of CSE, IU, LKO 8 ICS-453


Import statement
Class declaration
If exists, the package statement must be first one in the program. If exists, the import statement must be the
second one. Our class declaration is the third. Any order changes, it is a compilation error.
When the code is ready, the next job is compilation. We must compile with package notation. Package
notation uses –d compiler option as follows.
C:\Knrp > javac -d . Elephant.java
The –d compiler option creates a new folder called forest and places the Elephant.class in it. The dot (.) is an
operating system's environment variable that indicates the current directory. It is an instruction to the OS to
create a directory called forest and place the Elephant.class in it.
Using Custom-Defined Packages
After creating the package let us use it.
2nd step: Set the classpath from the target directory.
Let us assume D:\sumathi is the target directory. Let us access Elephant.class in forest package from here.
From the target directory set the classpath following way.
D:\sumathi> set classpath=C:\Knrp;%classpath%;
classpath is another environment variable which gives the address of the forest directory to the OS.
%classpath% informs the OS to append the already existing classpath to the current classpath that is right
now set.
3rd Step: Now finally, write a program from the target directory D:/sumathi and access the package.
D:\sumathi> notepad Animal.java
The above statement creates a file called Animal.java and write the code in it, say, as follows.
import forest.Elephant;
public class Animal
{
public static void main(String args[])
{
Elephant t1 = new Elephant ();
t1.getDetails("Everest", 50);
}
}
The compilation and execution is as usual as follows.
D:\sumathi> javac Animal.java
D:\sumathi> java Animal
Following is the output screen.
Importing the Package – Precautions
The following statement raises compilation error.

Dept of CSE, IU, LKO 9 ICS-453


import forest.*;
To work with the above statement, remove the source file Elephant.java file from C:\Knrp directory; else use
as import forest.Elephant.
Experiment # 2 A Program to create a customized Package in Java and import it in
some other Java Program. Details of which is under mentioned
Packages Name :- MyPack
Classes of it :- MyArraySort, MyStringPallindrome
1 Objective
 To apply the knowledge of custom Java Packages in Java.
 To apply the formulas in different classes and use them accordingly in
another Java Application.
 To apply the understanding of creating Packages and allocating access
right to the different classes within the packages.
 To understand the static import of java Packages and classes in some
other Java Application.

2 After completing this experiment you will be able to:


 Ready to implement different kinds of data member and member method
access strategies in Java Application.
 Ready to use and incorporate different logic within different clases of
different Java Packages.

3 Requirements: - Tools / Apparatus: Unix/Linux Operating System, Bash Shell,


OpenJDK and JRE installed on Machines
4 Solutions

/* FRAGEMENT CODE */
package MyPack;
public class MyArraySort
{
int arr[],lim;
public void sortMe()
{
// Code to sort the single dimension array if int type
}
}
package MyPack;
public class MyStringPallindrome
{
private String str;

Dept of CSE, IU, LKO 10 ICS-453


public MyStringPallindrome()
{str=””;}
public MyStringPallindrome(String s)
{str=s;}
public checkMe()
{
// Code to check whether the supplied String in str is Palindrome or not.
}
}

Now set your CLASSPATH environment variable as mentioned above.


// Code to import your customized Java Package name MyPack In PAKDEMO Class
import MyPack.MyArraySort;
import MyPack.MyStringPallindrome;
public class PAKDEMO
{
public static void main(String fg[])
{
MySortArray ms= new MySortArray();
ms.sortMe();
MyStringPallindrome pms= new MyStringPallindrome(fg[0]);
pms.checkMe();
}
}
Now Compile and execute your Java Application to get demonstrated with Java Customised
Application

5 Exercises:-
Q1 Write a program to print all the prime entries in an array in Same MyPack package
Q2 Write a program to print all non zero entries all positive and negative entries in same array of Q1.

6 For Further Reading Student May Refer to the following Books

1 Herbert Schildt, “THE COMPLETE REFRENCE:JAVA”, TMTT (Available in Departmental and


Central Library at University campus)

2 Core java vol. 1,2 By Cay Horstmann; Gary Cornell (Available in Departmental and Central Library
at University campus)

Dept of CSE, IU, LKO 11 ICS-453


Week # 3 Understanding Creation of an Applet using Swings

A Java applet is a special kind of Java program that a browser enabled with Java
technology can download from the internet and run. An applet is typically embedded inside a
web page and runs in the context of a browser. An applet must be a subclass of the
java.applet.Applet class. The Applet class provides the standard interface between the applet
and the browser environment.Swing provides a special subclass of the Applet class called
javax.swing.JApplet. The JApplet class should be used for all applets that use Swing
components to construct their graphical user interfaces (GUIs). The browser's Java Plug-in
software manages the lifecycle of an applet. Use a web server to test the examples in this
lesson. The use of local applets is not recommended, and local applets are blocked when the
security level setting in the Java Control Panel is set to High or Very High.

Event Handling Mechanism:- Under the JDK1.02 event model, components are notified of events
by the invocation of a method that matches a specific signature. Applets can override these
methods as well - providing customized event handlers to respond to the actions of a user. An
example of this is shown below, where an overridden mouseMove method responds to user events.

public boolean mouseMove( Event evt, int x, int y)


{
// Set message....
message = "mouseMove - x:" + x + " y: " + y;

// ... and repaint applet


repaint();

// Signal we have handled the event


return true;
}

In this method, we simply change the value of a member variable (message), and assign to it data
specific to the event. We call the repaint method, and our text is displayed to the user. Our applet
example responds to three different events (mouseMove, MouseExit, mouseDown), but there are many
events a custom component can respond to. Table One shows the major ones for subclasses of AWT
components, and Listing One the code for our example applet.

AWT Event Event signature


mouseDown mouseDown (Event evt, int x, int y)
mouseUp mouseUp (Event evt, int x, int y)
mouseEnter mouseEnter (Event evt, int x, int y)
mouseExit mouseExit (Event evt, int x, int y)
mouseMove mouseMove (Event evt, int x, int y)
mouseDrag mouseDrag (Event evt, int x, int y)
gotFocus gotFocus (Event evt, Object what)
lostFocus lostFocus (Event evt, Object what)

Dept of CSE, IU, LKO 12 ICS-453


keyDown keyDown (Event evt, int key)
keyUp keyUp (Event evt, int key)
Action action (Event evt, Object what)

Table 1.0 - Major AWT component events

Experiment #3 A Program to create an Applet demonstrating various drawing methods of Applet


and demonstrate event handling mechanism

1 Objective
 Learning the working of Java Applet Technologies in Java Programming
Model.
 How to recognize different stages of Applet Life Cycle.
 Learning how to create an Applet by extending Applet class
 How to create customized events by implementing various interface
methods.

2 After completing this experiment you will be able to:

 Ready to use Applet Creation Strategies in your Java Programming


Development Environment.
 Ready to create multiple Applet to from various 2D and 3D figures by
using dedicated Applet methods.
 Ready to analyze different stages of Applet Life cycle..
 Ready to manage your web page by embedding Applet of varying
dimension as per user requirement.

3 Requirements: - Tools / Apparatus: Unix/Linux Operating System, Bash Shell,


OpenJDK and JRE installed on Machines
4 Solution
/*JAVA CODE */

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

public class EventApplet extends Applet implements ActionListener{

Dept of CSE, IU, LKO 13 ICS-453


Button b;

TextField tf;

public void init(){

tf=new TextField();

tf.setBounds(30,40,150,20);

b=new Button("Click");

b.setBounds(80,150,60,50);

add(b);add(tf);

b.addActionListener(this);

setLayout(null);}

public void actionPerformed(ActionEvent e){

tf.setText("Welcome"); } }

5 Exercises:-
Q1 Write a Program to demonstrate the events handling mechanism in Applet
Programming Development Environment.

Q2 Write a Java Applet to demonstrate the use of various drawing methods and embed it
on web page.

6 For Further Reading Student May Refer to the following Books

1 Herbert Schildt, “THE COMPLETE REFRENCE:JAVA”, TMTT (Available in Departmental


and Central Library at University campus)

2 Core java vol. 1,2 By Cay Horstmann; Gary Cornell (Available in Departmental and Central
Library at University campus)

Dept of CSE, IU, LKO 14 ICS-453


Week # 4 Introducing Socket Programming
The term network programming refers to writing programs that execute across multiple
devices (computers), in which the devices are all connected to each other using a network.
The java.net package of the J2SE APIs contains a collection of classes and interfaces that
provide the low-level communication details, allowing you to write programs that focus
on solving the problem at hand.
The java.net package provides support for the two common network protocols:
 TCP: TCP stands for Transmission Control Protocol, which allows for reliable
communication between two applications. TCP is typically used over the Internet
Protocol, which is referred to as TCP/IP.
 UDP: UDP stands for User Datagram Protocol, a connection-less protocol that
allows for packets of data to be transmitted between applications.
This tutorial gives good understanding on the following two subjects:
 Socket Programming: This is most widely used concept in Networking and it has
been explained in very detail.
 URL Processing: This would be covered separately. Click here to learn about URL
Processing in Java language.
The ServerSocket class has four constructors:
SN Methods with Description
public ServerSocket(int port) throws IOException
1 Attempts to create a server socket bound to the specified port. An exception occurs
if the port is already bound by another application.
public ServerSocket(int port, int backlog) throws IOException
2 Similar to the previous constructor, the backlog parameter specifies how many
incoming clients to store in a wait queue.
public ServerSocket(int port, int backlog, InetAddress address) throws
IOException
Similar to the previous constructor, the InetAddress parameter specifies the local IP
3
address to bind to. The InetAddress is used for servers that may have multiple IP
addresses, allowing the server to specify which of its IP addresses to accept client
requests on
public ServerSocket() throws IOException
4 Creates an unbound server socket. When using this constructor, use the bind()
method when you are ready to bind the server socket
If the ServerSocket constructor does not throw an exception, it means that your
application has successfully bound to the specified port and is ready for client requests.
Here are some of the common methods of the ServerSocket class:
When the ServerSocket invokes accept(), the method does not return until a client
connects. After a client does connect, the ServerSocket creates a new Socket on an
unspecified port and returns a reference to this new Socket. A TCP connection now exists

Dept of CSE, IU, LKO 15 ICS-453


between the client and server, and communication can begin.
Socket Class Methods:
The java.net.Socket class represents the socket that both the client and server use to
communicate with each other. The client obtains a Socket object by instantiating one,
whereas the server obtains a Socket object from the return value of the accept() method.
The Socket class has five constructors that a client uses to connect to a server:
When the Socket constructor returns, it does not simply instantiate a Socket object but it
actually attempts to connect to the specified server and port.
Some methods of interest in the Socket class are listed here. Notice that both the client
and server have a Socket object, so these methods can be invoked by both the client and
server.
InetAddress Class Methods:
This class represents an Internet Protocol (IP) address. Here are following usefull
methods which you would need while doing socket programming:
Socket Client Example:
The following GreetingClient is a client program that connects to a server by using a
socket and sends a greeting, and then waits for a response.
Socket Server Example:
The following GreetingServer program is an example of a server application that uses the
Socket class to listen for clients on a port number specified by a command-line argument:

Experiment #4 A Program to demonstrate the use of InetAddress, UserDatagramSocket,


UserDatagramPacket classes and interfaces
1 Objective
 Learning the working knowledge of Java Database Connectivity in Java
Programming Model.
 How to recognize different steps and stages of JDBC.
 Learning how to create database and throw query to it to get back record
from the database
 How to write DDL and DML type of queries

2 After completing this experiment you will be able to:

 Ready to use JDBC API to check and perform DML & DDL queries
 Ready to create Java Database connectivity Program to talk to your
relational database of various domains.
 Ready to analyze different stages involved in JDBC.
 Ready to manage your Application by persistence of hidden data of the
Applicaion

Dept of CSE, IU, LKO 16 ICS-453


3 Requirements: - Tools / Apparatus: Unix/Linux Operating System, Bash Shell,
OpenJDK and JRE installed on Machines
4 Solution
/*JAVA CODE */
// File Name GreetingServer.java

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

public class GreetingServer extends Thread


{
private ServerSocket serverSocket;

public GreetingServer(int port) throws IOException


{
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
}

public void run()


{
while(true)
{
try
{
System.out.println("Waiting for client on port " +
serverSocket.getLocalPort() + "...");
Socket server = serverSocket.accept();
System.out.println("Just connected to "
+ server.getRemoteSocketAddress());
DataInputStream in =
new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out =
new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for connecting to "
+ server.getLocalSocketAddress() + "\nGoodbye!");
server.close();
}catch(SocketTimeoutException s)
{
System.out.println("Socket timed out!");
break;

Dept of CSE, IU, LKO 17 ICS-453


}catch(IOException e)
{
e.printStackTrace();
break;
}
}
}
public static void main(String [] args)
{
int port = Integer.parseInt(args[0]);
try
{
Thread t = new GreetingServer(port);
t.start();
}catch(IOException e)
{
e.printStackTrace();
}
}
}

Compile client and server and then start server as follows:

$ java GreetingServer 6066

Waiting for client on port 6066...

Check client program as follows:

$ java GreetingClient localhost 6066

Connecting to localhost on port 6066

Just connected to localhost/127.0.0.1:6066

Server says Thank you for connecting to /127.0.0.1:6066

Goodbye!

Dept of CSE, IU, LKO 18 ICS-453


5 Exercises:-
Q1 Write a Program to implement TCP in Java Programming Model

Q2 Write a Java program to implement UDP in Java Programming Model.

6 For Further Reading Student May Refer to the following Books

3 Herbert Schildt, “THE COMPLETE REFRENCE:JAVA”, TMTT (Available in Departmental and


Central Library at University campus)

4 Core java vol. 1,2 By Cay Horstmann; Gary Cornell (Available in Departmental and Central Library
at University campus)

Dept of CSE, IU, LKO 19 ICS-453


Week # 5 Understanding the concept of Remote Methods Invocations

The distributed Hello World example uses a simple client to make a remote method invocation to a
server which may be running on a remote host. The client receives the "Hello, world!" message
from the server.

This tutorial has the following steps:

 Define the remote interface


 Implement the server
 Implement the client
 Compile the source files
 Start the Java RMI registry, server, and client

The files needed for this tutorial are:

 Hello.java - a remote interface


 Server.java - a remote object implementation that implements the remote interface
 Client.java - a simple client that invokes a method of the remote interface

Note: For the remainder of this tutorial, the terms "remote object implementation" and "implementation
class" are used interchangeably to refer to the class example.hello.Server, which implements
a remote interface.

Define the remote interface


A remote object is an instance of a class that implements a remote interface. A remote interface extends
the interface java.rmi.Remote and declares a set of remote methods. Each remote method must
declare java.rmi.RemoteException (or a superclass of RemoteException) in its
throws clause, in addition to any application-specific exceptions.

Here is the interface definition for the remote interface used in this example,
example.hello.Hello. It declares just one method, sayHello, which
returns a string to the caller

Experiment #5 A Program to implement RMI in Java


1 Objective
 Learning Basics of Remote Methods Invocations
 Designing remote interfaces and generating stubs and skeletons for
communication of Client and server Architecture
 How to remotely perform the function or task using Java Technology.

2 After completing this experiment you will be able to:

Dept of CSE, IU, LKO 20 ICS-453


 Create Remote Methods that can be easily called or accessed from remote
machine
 Learning basics of Java RMI
 Understanding basics of Stubs and skeleton used in Java RMI.
 How to run RMI on different types of Machines.

3 Requirements: - Tools / Apparatus: Unix/Linux Operating System, Bash Shell,


OpenJDK and JRE installed on Machines
4 Solution
/*JAVA CODE */

Interface for Java RMI


import java.rmi.*;
public interface Adder extends Remote{

public int add(int x,int y)throws RemoteException;


}

Implemention Class for RMI


import java.rmi.*;
import java.rmi.server.*;

public class AdderRemote extends UnicastRemoteObject implements Adder{

AdderRemote()throws RemoteException{
super();
}
public int add(int x,int y){return x+y;}
}
import java.rmi.*;
import java.rmi.server.*;
public class AdderRemote extends UnicastRemoteObject implements Adder{
AdderRemote()throws RemoteException{
super();
}
public int add(int x,int y){return x+y;}
}
rmic AdderRemote
rmiregistry 5000
For running this rmi example,
1) compile all the java files
javac *.java
2)create stub and skeleton object by rmic tool
rmic AdderRemote
3)start rmi registry in one command prompt
rmiregistry 5000
4)start the server in another command prompt

Dept of CSE, IU, LKO 21 ICS-453


java MyServer
5)start the client application in another command prompt
java MyClient

5 Exercises:-
Q1 Write a Program to implement Remote Method Invocations to check whether a file is
present in the client machine or not..

6 For Further Reading Student May Refer to the following Books

Herbert Schildt, “THE COMPLETE REFRENCE:JAVA”, TMTT (Available in Departmental and


Central Library at University campus)

Core java vol. 1,2 By Cay Horstmann; Gary Cornell (Available in Departmental and Central Library at
University campus)

Dept of CSE, IU, LKO 22 ICS-453


Week # 6 Introduction of Multicast socket Programming in Java
Application

Multicasting in Java
1. Introduction
This article deals primarily with the subject of multicast communication in Java.
2. Sending multicast datagrams
In order to send any kind of datagram in Java, one needs a java.net.DatagramSocket:
DatagramSocket socket = new DatagramSocket();
This sample code creates the socket and a datagram to send and then simply sends the
same datagram every second:
DatagramSocket socket = new DatagramSocket();
byte[] b = new byte[DGRAM_LENGTH];
DatagramPacket dgram;
dgram = new DatagramPacket(b, b.length,
InetAddress.getByName(MCAST_ADDR), DEST_PORT);
System.err.println("Sending " + b.length + " bytes to " +
dgram.getAddress() + ':' + dgram.getPort());
while(true) {
System.err.print(".");
socket.send(dgram);
Thread.sleep(1000);
}
Valid values for the constants are:
•DGRAM_LENGTH: anything from 0 to 65507 (see section 5),
•MCAST_ADDR: any class D address (see appendix D), from 224.0.0.0 to 235.1.1.1,
•DEST_PORT: an unsigned 16-bit integer, eg. 6789 or 7777.
3. Receiving multicast datagrams
One can use a normal DatagramSocket to send and receive multicast datagrams as seen
in the section 2. In order to receive multicast datagrams, however, one needs a
MulticastSocket. The reason for this is simple, additional work needs to be done to
control and receive multicast traffic by all the protocol layers below UDP.
The example given below, opens a multicast socket, binds it to a specific port and joins
a specific multicast group:
byte[] b = new byte[BUFFER_LENGTH];
DatagramPacket dgram = new DatagramPacket(b, b.length);
MulticastSocket socket =
new MulticastSocket(DEST_PORT); // must bind receive side
socket.joinGroup(InetAddress.getByName(MCAST_ADDR));
while(true) {
socket.receive(dgram); // blocks until a datagram is received
System.err.println("Received " + dgram.getLength() +
" bytes from " + dgram.getAddress());

Dept of CSE, IU, LKO 23 ICS-453


dgram.setLength(b.length); // must reset length field!
}
Experiment # 6 A Program to implement MulticastSocket Program in Java
1 Objective
 Learning Basics of Multicast Socket And DatagramPacket classes of java.net
packages
 Designing customized messages to send from one Machine or IP to a group
of Machine or IPs
 How to implement Multicast send data through Java Technology.

2 After completing this experiment you will be able to:

 Create Multicasting client arrays and sending IP of the Macj=hine to


communicate
 Learning basics of Java MulticastSocket and DatagramPacket’s Data
structure
 Understanding basics of some intermediate steps required to get
communicated from one pc to array of PCsusing Java Applications.

3 Requirements: - Tools / Apparatus: Unix/Linux Operating System, Bash Shell,


OpenJDK and JRE installed on Machines
4 Solution
/*JAVA CODE */
import java.io.*;

public class QuoteServer {


public static void main(String[] args) throws IOException {
new QuoteServerThread().start();
}
}
The QuoteServerThread Class
The QuoteServerThread class implements the main logic of the quote server:
import java.io.*;
import java.net.*;
import java.util.*;
public class QuoteServerThread extends Thread {
protected DatagramSocket socket = null;
protected BufferedReader in = null;
protected boolean moreQuotes = true;
public QuoteServerThread() throws IOException {
this("QuoteServerThread");
}

Dept of CSE, IU, LKO 24 ICS-453


public QuoteServerThread(String name) throws IOException {
super(name);
socket = new DatagramSocket(4445);
try {
in = new BufferedReader(new FileReader("one-liners.txt"));
} catch (FileNotFoundException e) {
System.err.println("Could not open quote file. Serving time instead.");
}
}
public void run() {
while (moreQuotes) {
try {
byte[] buf = new byte[256];
// receive request
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
// figure out response
String dString = null;
if (in == null)
dString = new Date().toString();
else
dString = getNextQuote();
buf = dString.getBytes();

// send the response to the client at "address" and "port"


InetAddress address = packet.getAddress();
int port = packet.getPort();
packet = new DatagramPacket(buf, buf.length, address, port);
socket.send(packet);
} catch (IOException e) {
e.printStackTrace();
moreQuotes = false;
}
}
socket.close();
}

protected String getNextQuote() {


String returnValue = null;
try {
if ((returnValue = in.readLine()) == null) {
in.close();
moreQuotes = false;
returnValue = "No more quotes. Goodbye.";

Dept of CSE, IU, LKO 25 ICS-453


}
} catch (IOException e) {
returnValue = "IOException occurred in server.";
}
return returnValue;
}
}
When created, the QuoteServerThread creates a DatagramSocket on port 4445 (arbitrarily chosen).
This is the DatagramSocket through which the server communicates with all of its clients.
public QuoteServerThread() throws IOException {
this("QuoteServer");
}
public QuoteServerThread(String name) throws IOException {
super(name);
socket = new DatagramSocket(4445);
try {
in = new BufferedReader(new FileReader("one-liners.txt"));
} catch (FileNotFoundException e)
System.err.println("Couldn't open quote file. " +"Serving time instead.");
}
}

Exercise

Q1 A Program to implement multicast programming in Java Applicagtions.

Q2 A Program to send customized methods to different IPs Connected to main Machines

6 For Further Reading Student May Refer to the following Books

Herbert Schildt, “THE COMPLETE REFRENCE:JAVA”, TMTT (Available in Departmental and


Central Library at University campus)

Core java vol. 1,2 By Cay Horstmann; Gary Cornell (Available in Departmental and Central Library at
University campus)

Dept of CSE, IU, LKO 26 ICS-453


Week # 7 Introduction OF TSR

In computers, a terminate and stay resident program (commonly referred to by


the initialism TSR) is a computer program that uses a system call in DOSoperating
systems to return control of the computer to the operating system, as though the program
has quit, but stays resident in computer memory so it can be reactivated by a hardware or
software interrupt.[1] This technique partially overcame DOS operating systems' limitation
of executing only one program, or task, at a time. TSR is unique to DOS and not used in
Windows.
Some terminate and stay resident programs were utility programs that a computer user
might call up several times a day, while working in another program, using
ahotkey. Borland Sidekick was an early and popular example of this type. Other TSRs serve
as device drivers for hardware that the operating system did not directly support. Normally
in DOS operating systems, only one program can run at any given time. To stop running, it
gives control back to the DOS shell program, COMMAND.COM, using the system call INT
21h/4Ch.[2] The memory and system resources that were used by the program are then
marked as unused. This in effect makes it impossible to restart parts of it again without
reloading it from scratch. However, if a program ends with the system call INT 27h or INT
21h/31h, the operating system does not reuse a certain specified part of the program's
memory.

The original call, INT 27h, is called 'terminate but stay resident', hence the name 'TSR'.
Using this call, a program can make up to 64 KB of its memory resident. MS-DOS version
2.0 introduced an improved call, INT 21h/function 31h ('Keep Process'), which removed
this limitation and let the program return an exit code. Before making this call, the program
can install one or several interrupt handlers pointing into itself, so that it can be called again.
Installing a hardware interrupt vector allows such a program to react to hardware events.
Installing a software interrupt vector allows it to be called by the currently running program.
Installing a timer interrupt handler allows a TSR to run periodically (see ISA and
programmable interval timer, especially the section "IBM PC compatible").

The typical method of utilizing an interrupt vector involves reading its present value (the
address), storing it within the memory space of the TSR, and installing a pointer to its own
code. The stored address is called before or after the TSR has received the interrupt and has
finished its processing, in effect forming a singly linked list of interrupt handlers, also called

Dept of CSE, IU, LKO 27 ICS-453


interrupt service routines, or ISRs. This procedure of installing ISRs is called chaining or
hooking an interrupt or an interrupt vector.

By chaining the interrupt vectors TSR programs could take complete control of the
computer. A TSR could have one of two behaviors:

Take complete control of an interrupt by not calling other TSRs that had previously altered
the same interrupt vector.
Cascade with other TSRs by calling the old interrupt vector. This could be done before or
after they executed their actual code. This way TSRs could form a chain of programs where
each one calls the next one.
The 'terminate and stay resident' method was used by most DOS viruses which could either
take control of the PC or stay in the background. Viruses would react to disk I/O or
execution events by infecting executable (.EXE or .COM) files when they were run and data
files when they were opened.

Parts of DOS itself, especially in DOS versions 5.0 and later, used this same technique to
perform useful functions, such as the DOSKEY command-line editor and various other
installable utilities which were installed by running them at the command line (manually,
from AUTOEXEC.BAT or through INSTALL from within CONFIG.SYS) rather than
loading them as device drivers through DEVICE statements in CONFIG.SYS.

A TSR program can be loaded at any time; sometimes, they are loaded immediately after
the operating system's boot, by being explicitly loaded in the AUTOEXEC.BAT batch
program, or alternatively at the user's request (for example, Borland's Sidekick and Turbo
Debugger, Quicken's QuickPay, or FunStuff Software's Personal Calendar). These programs
will, as 'TSR' implies, stay resident in memory while other programs are executing. Some of
them do not have an option for unloading themselves from memory, so calling TSR means
the program will remain in memory until a reboot. However unloading is possible
externally, using utilities like the MARK.EXE/RELEASE.EXE combo by TurboPower
Software or soft reboot TSRs which will catch a specific key combination and release all
TSRs loaded after them. As the chain of ISRs is singly linked, there is no provision for
discovering the previous handler's address (other than attempting to trace back the interrupt
chain), or to inform its predecessor that it needs to update its "next address to which to
jump" not to point to the TSR which desires to remove itself, so that in order to safely

Dept of CSE, IU, LKO 28 ICS-453


unload TSRs in the middle of a chain, stubs had to be left in memory in most cases, thereby
causing memory fragmentation

Experiment #7 A Program to implement TSR Programming


1 Objective
 Learning Basics of Transient but Stay resident Programs
 How to code a TSR Program using C/C++ programming language.

2 After completing this experiment you will be able to:

 Create TSR Program to implement clock design using C/C++ programming


model.
 Understanding basics of some DOS internal calls module to send signals to
OS regarding Completion of Job.

3 Requirements: - Tools / Apparatus: Unix/Linux Operating System, Bash Shell,


OpenJDK and JRE installed on Machines
4 Solution

/* C/C++ CODE TO DEMONSTRATE TSR */

#include"dos.h"
#include<conio.h>
#include<stdlib.h>

//interrupt declarations
void interrupt (*prevtimer)();
void interrupt mytimer();
void writechar(char ch,int row,int col,int attr);

//a far pointer that will access video memory


char far* scr;
int a,b;

//our real program goes from here


void main()
{
scr=(char far*) 0xb8000000;
prevtimer=getvect( 8 );
setvect(8,mytimer);
keep(0,1000);
}

//timer function

Dept of CSE, IU, LKO 29 ICS-453


void interrupt mytimer()
{
a=random(25);
b=random(80);
writechar(' ',a,b,0);
(*prevtimer)();
}

//function that writes picked up character


void writechar(char ch,int row,int col,int attr)
{
*(scr+row*160+col*2)=ch;
*(scr+row*160+col*2+1)=attr;
}

Exercise

Q1 A Program to implement TSR in Java


Q2 A Program that act as a TSR tutorial in Java

6 For Further Reading Student May Refer to the following Books

Herbert Schildt, “THE COMPLETE REFRENCE:JAVA”, TMTT (Available in Departmental and


Central Library at University campus)

Core java vol. 1,2 By Cay Horstmann; Gary Cornell (Available in Departmental and Central Library at
University campus)

Dept of CSE, IU, LKO 30 ICS-453

S-ar putea să vă placă și