25
http://www.letsgetgyan.com/ds-practical-theory-print- out/ Practical No: 01 Aim: Write a program for implementing Client Server communication model. Theory: TCP and UDP provide the communication capabilities of the Internet in a form that is useful for application programs TCP and UDP can be viewed as a faithful reflection at the application programming level of the communication facilities that IPv4 has to offer. TCP and UDP, as transport protocols, must provide process- to-process communication. This is accomplished by the use of ports. Port numbers are used for addressing messages to processes within a particular computer and are valid only within that computer. Once an IP packet has been delivered to the destination host, the TCP- or UDP-layer software dispatches it to a process via a specific port at that host. Java API for UDP datagrams • The Java API provides datagram communication by means of two classes: DatagramPacket and DatagramSocket. DatagramPacket: This class provides a constructor that makes an instance out of an array of bytes comprising a message, the length of the message and the Internet

DS_Final_Theory.docx

Embed Size (px)

Citation preview

Page 1: DS_Final_Theory.docx

http://www.letsgetgyan.com/ds-practical-theory-print-out/

Practical No: 01

Aim: Write a program for implementing Client Server communication model.

Theory:

TCP and UDP provide the communication capabilities of the Internet in a form that is useful for application programs TCP and UDP can be viewed as a faithful reflection at the application programming level of the communication facilities that IPv4 has to offer. TCP and UDP, as transport protocols, must provide process-to-process communication. This is accomplished by the use of ports. Port numbers are used for addressing messages to processes within a particular computer and are valid only within that computer. Once an IP packet has been delivered to the destination host, the TCP- or UDP-layer software dispatches it to a process via a specific port at that host.

Java API for UDP datagrams • The Java API provides datagram communication by means of two classes: DatagramPacket and DatagramSocket. DatagramPacket: This class provides a constructor that makes an instance out of an array of bytes comprising a message, the length of the message and the Internet address and local port number of the destination socket, as follows:

Datagram packet

array of bytes containing message

Length of message

Internet address

port number

Page 2: DS_Final_Theory.docx

An instance of DatagramPacket may be transmitted between processes when one process sends it and another receives it.This class provides another constructor for use when receiving a message. Its arguments specify an array of bytes in which to receive the message and the length of the array. A received message is put in the DatagramPacket together with its length and the Internet address and port of the sending socket. The message can be retrieved from the DatagramPacket by means of the method getData. The methods getPort and getAddress access the port and Internet address.

DatagramSocket: This class supports sockets for sending and receiving UDP datagrams. It provides a constructor that takes a port number as its argument, for use by processes that need to use a particular port. It also provides a no-argument constructor that allows the system to choose a free local port. These constructors can throw a SocketException if the chosen port is already in use or if a reserved port (a number below 1024) is specified when running over UNIX. The class DatagramSocket provides methods that include the following: send and receive: These methods are for transmitting datagrams between a pair of sockets. The argument of send is an instance of DatagramPacket containing a message and its destination. The argument of receive is an emptyDatagramPacket in which to put the message, its length and its origin. The methods send and receive can throw IOExceptions. setSoTimeout: This method allows a timeout to be set. With a timeout set, the receivemethod will block for the time specified and then throw an InterruptedIOException. connect: This method is used for connecting to a particular remote port and Internet address, in which case the socket is only able to send messages to and receive messages from that address.

Java API for TCP streams • The Java interface to TCP streams is provided in the classes ServerSocket and Socket:ServerSocket: This class is intended for use by a server to create a socket at a server port for listening for connect requests

Page 3: DS_Final_Theory.docx

from clients. Its accept method gets a connect request from the queue or, if the queue is empty, blocks until one arrives. The result of executing accept is an instance of Socket – a socket to use for communicating withthe client.

Socket: This class is for use by a pair of processes with a connection. The client uses a constructor to create a socket, specifying the DNS hostname and port of a server. This constructor not only creates a socket associated with a local port but also connects it to the specified remote computer and port number. It can throw an UnknownHostException if the hostname is wrong or an IOException if an IO error occurs. The Socket class provides the methods getInputStream and getOutputStream for accessing the two streams associated with a socket. The return types of these methods are InputStream and OutputStream, respectively – abstract classes thatdefine methods for reading and writing bytes. The return values can be used as the arguments of constructors for suitable input and output streams. Our example uses DataInputStream and DataOutputStream, which allow binary representations of primitive data types to be read and written in a machine-independent manner.

Page 4: DS_Final_Theory.docx

Practical No: 02

Aim: Write a program to show the object communication using RMI.

Remote method invocation: Remote method invocation (RMI) strongly resembles remote procedure calls but in a world of distributed objects. With this approach, a calling object can invoke a method in a remote object. As with RPC, the underlying details are generally hidden from the user. RMI implementations may, though, go further by supporting object identity and the associated ability to pass object identifiers as parameters in remote calls. They also benefit more generally from tighter integration into object-oriented languagesIn the 1990s, the object-based programming model was extended to allow objects in different processes to communicate with one another by means of remote method invocation (RMI). RMI is an extension of local method invocation that allows an object living

Page 5: DS_Final_Theory.docx

in one process to invoke the methods of an object living in another process.Remote interfaces are defined by extending an interface called Remote provided in the java.rmi package. The methods must throw RemoteException, but application-specific exceptions may also be thrown.

Parameter and result passing • In Java RMI, the parameters of a method are assumed to be input parameters and the result of a method is a single output parameter. Any object that is serializable – that is, that implements the Serializable interface – can be passed as an argument or result in Java RMI. All primitive types and remote objects are serializable. Classes for arguments and result values are downloaded to the recipient by the RMI system where necessary.Passing remote objects: When the type of a parameter or result value is defined as a remote interface, the corresponding argument or result is always passed as a remote object reference. When a remote object reference is received, it can be used to make RMI calls on the remote object to which it refers.Passing non-remote objects: All serializable non-remote objects are copied and passed by value. When an object is passed by value, a new object is created in the receiver’s process. The methods of this new object can beinvoked locally, possibly causing its state to differ from the state of the original object in the sender’s process.

The Naming class of Java RMIregistryvoid rebind (String name, Remote obj)This method is used by a server to register the identifier of a remote object by name,

void bind (String name, Remote obj)This method can alternatively be used by a server to register a remote object by name,but if the name is already bound to a remote object reference an exception is thrown.void unbind (String name, Remote obj)This method removes a binding.

Page 6: DS_Final_Theory.docx

Remote lookup(String name)This method is used by clients to look up a remote object by name . A remote object reference is returned.String [] list()This method returns an array of Strings containing the names bound in the registry.

RMIregistry • The RMIregistry is the binder for Java RMI. An instance of RMIregistry should normally run on every server computer that hosts remote objects. It maintains table mapping textual, URL-style names to references to remote objects hosted on that computer. It is accessed by methods of the Naming class, whose methods take as anargument a URL-formatted string of the form://computerName:port/objectNamewhere computerName and port refer to the location of the RMIregistry. If they are omitted, the local computer and default port are assumed. Its interface offers themethods shown above, in which the exceptions are not listed – all of the methods can throw a RemoteException.Used in this way, clients must direct their lookup enquiries to particular hosts. Alternatively, it is possible to set up a system-wide binding service. To achieve this, it is necessary to run an instance of the RMIregistry in the networked environment and then use the class LocateRegistry, which is in java.rmi.registry, to discover this registry.More specifically, this class contains a getRegistry method that returns an object of type Registry representing the remote binding service:

public static Registry getRegistry() throws RemoteException

Following this, it is then necessary to issue a call of rebind on this returned Registry object to establish a connection with the remote RMIregistry.

Page 7: DS_Final_Theory.docx

Java classes supporting RMI • Figure the inheritance structure of the classes supporting Java RMI servers. The only class that the programmer need be aware of isUnicastRemoteObject, which every simple servant class needs to extend. The classUnicastRemoteObject extends an abstract class called RemoteServer, which providesabstract versions of the methods required by remote servers. UnicastRemoteObject wasthe first example of RemoteServer to be provided. Another called Activatable isavailable for providing activatable objects. Further alternatives might provide forreplicated objects. The class RemoteServer is a subclass of RemoteObject that has aninstance variable holding the remote object reference and provides the followingmethods:equals This method compares remote object references.toString: This method gives the contents of the remote object reference as a String.readObject, writeObject: These methods deserialize/serialize remote objects.In addition, the instanceOf operator can be used to test remote objects.

Page 8: DS_Final_Theory.docx

Practical No: 03

Aim: Show the implementation of Remote Procedure Call.

Remote procedure calls: The concept of a remote procedure call (RPC), initially attributed to Birrell and Nelson [1984], represents a major intellectual breakthrough in distributed computing. In RPC, procedures in processes on remote computers can be called as if they are procedures in the local address space. The underlying RPC system then hides important aspects of distribution, including the encoding and decoding of parameters and results, the passing of messages and the preserving of the required semantics for the procedure call. This approach directly and elegantly supports client-server computing with servers offering a set of operations through an service interface and clients calling these operations directly as if they were available locally. RPC systems therefore offer (at a minimum) access and locationtransparency.

In computer science, a remote procedure call (RPC) is an inter-process communication that allows a computer program to cause a subroutine or procedure to execute in another address space (commonly on another computer on a shared network) without the programmer explicitly coding the details for this remote interaction. That is, the programmer writes essentially the same code whether the subroutine is local to the executing program, or remote. When the software in question uses object-oriented principles, RPC is called remote invocation or remote method invocation.Message passing

Page 9: DS_Final_Theory.docx

An RPC is initiated by the client, which sends a request message to a known remote server to execute a specified procedure with supplied parameters. The remote server sends a response to the client, and the application continues its process. While the server is processing the call, the client is blocked (it waits until the server has finished processing before resuming execution), unless the client sends an asynchronous request to the server, such as an XHTTP call. There are many variations and subtleties in various implementations, resulting in a variety of different (incompatible) RPC protocols.An important difference between remote procedure calls and local calls is that remote calls can fail because of unpredictable network problems. Also, callers generally must deal with such failures without knowing whether the remote procedure was actually invoked.Idempotent procedures (those that have no additional effects if called more than once) are easily handled, but enough difficulties remain that code to call remote procedures is often confined to carefully written low-level subsystems.

Sequence of events during a RPC

1. The client calls the client stub. The call is a local procedure call, with parameters pushed on to the stack in the normal way.

2. The client stub packs the parameters into a message and makes a system call to send the message. Packing the parameters is called marshalling.

3. The client's local operating system sends the message from the client machine to the server machine.

4. The local operating system on the server machine passes the incoming packets to the server stub.

5. The server stub unpacks the parameters from the message. Unpacking the parameters is called unmarshalling.

6. Finally, the server stub calls the server procedure. The reply traces the same steps in the reverse direction.

Standard contact mechanisms

To let different clients access servers, a number of standardized RPC systems have been created. Most of these use an interface description language (IDL) to let various platforms call the RPC. The IDL files can then be used to generate code to

Page 10: DS_Final_Theory.docx

interface between the client and server. The most common tool used for this is RPCGEN [citation needed].

Practical No: 04

Aim: Show the implementation of web services.

Theory:

Creating the Web Service:

A web service is an web application which is basically a class consisting of methods that could be used by other applications. It also follows a code-behind architecture like the ASP.Net web pages, although it does not have an user interface.

To understand the concept let us create a web service that will provide stock price information. The clients can query about the name and price of a stock based on the stock symbol. To keep this example simple, the values are hardcoded in a two-dimensional array. This web service will have three methods:

A defaullt HelloWorld method A GetName Method A GetPrice Method

Page 11: DS_Final_Theory.docx

Practical No: 05

Aim: Write a program to execute any one mutual exclusion algorithm.

Mutual Exclusion Using Token Ring :Here is a program to apply mutual exclusion using Token Ring algorithm. The program contains two or more clients and a server. Token is circulated among all client sequentially a client which has a token has right to send message to the server.

Theory: Systems involving multiple processes are often most easily programmed using critical regions. When a process has to read or update certain shared data structures, it first enters a critical region to achieve mutual exclusion and ensure that no other process will use the shared data structures at the same time. Token Ring Algorithm – It is a completely different approach to achieving mutual exclusion in a distributing system illustrated in the below diagram.

Page 12: DS_Final_Theory.docx

Here in fig.(a),we have a bus network with no inherent ordering of the processes. In software, a logical ring is constructed in which each process is assigned a position in a ring as shown in fig.(b).The ring positions may be allocated in numerical order of network addresses or some other means. When the ring is initialized, process 0 is given a token. The token circulates around the ring. It is passed from process k to process k+1 in point-to-point messages. When a process acquires the token from its neighbour, it checks to see if it is attempting to enter a critical region. If so, the process enters the region, does all the work it needs to, and leaves the region. After it has exited, it passes the token along the ring. It is not permitted to enter a second region using the same token. If a process is handed the token by its neighbour and is not interested in entering a critical region, it just passes it along. As a result, when no processes want to enter any critical regions, the token just circulates at high speed around the ring.

Only one process has the token at any instant, so only one process can actually be in a critical region. Once a process

Page 13: DS_Final_Theory.docx

decides it wants to enter a critical region, it worst it will have to wait for every other process to enter and leave one critical region.

If the token is ever lost, it must be regenerated. In fact, detecting that it is lost is difficult, since the amount of time between successive appearances of the token on the network is unbounded. The fact that token has not been spotted for an hour does not mean that it has been lost; somebody may still be using it.

The algorithm also runs into trouble if a process crashes, but recovery is easier than in other cases. If we require a process receiving the token to acknowledge receipt, a dead process will be detected when its neighbour tries to give it the token and fails. At that point the dead process can be removed from the group, and the token holder can throw the token over the head of the dead process to the next number down the line, or the one that, if necessary. By doing so requires that everyone maintains the current ring configuration.

Practical No: 06

Aim: Write a program to implement any one election algorithm.

Theory: An algorithm for choosing a unique process to play a particular role is called an election algorithm.

A ring-based election algorithm: Each process pi has a communication channel to the next process in the ring, p (i + 1)mod N and all messages are sent

Page 14: DS_Final_Theory.docx

clockwise around the ring. We assume that no failures occur, and that the system is asynchronous. The goal of this algorithm is to elect a single process called the coordinator, which is the process with the largest identifier. Initially, every process is marked as a non-participant in an election. Any process can begin an election. It proceeds by marking itself as a participant, placing its identifier in an election message and sending it to its clockwise neighbour. When a process receives an election message, it compares the identifier in the message with its own. If the arrived identifier is greater, then it forwards the message to its neighbour. If the arrived identifier is smaller and the receiver is not a participant, then it substitutes its own identifier in the message and forwards it; but it does not forward the message if it is already a participant. On forwarding an election message in any case, the process marks itself as a participant.

If, however, the received identifier is that of the receiver itself, then this process’s identifier must be the greatest, and it becomes the coordinator. The coordinator marks itself as a non-participant once more and sends an elected message to its neighbour, announcing its election and enclosing its identity. When a process pi receives an elected message, it marks itself as a nonparticipant, sets its variable electedi to the identifier in the message and, unless it is the new coordinator, forwards the message to its neighbour.

It is easy to see that condition E1 is met. All identifiers are compared, since a process must receive its own identifier back before sending an elected message. For any two processes, the one with the larger identifier will not pass on the other’s identifier. It is therefore impossible that both should receive their own identifier back. Condition E2 follows immediately from the guaranteed traversals of the ring (there are no failures). Note how the non-participant and participant states are used so that duplicate messages arising when two processes start an election at the same time are

Page 15: DS_Final_Theory.docx

extinguished as soon as possible, and always before the ‘winning’ election result has been announced.

If only a single process starts an election, then the worst-performing case is when its anti-clockwise neighbour has the highest identifier. A total of N – 1 messages are then required to reach this neighbour, which will not announce its election until its identifier has completed another circuit, taking a further N messages. The elected message is then sent N times, making 3N – 1 messages in all. The turnaround time is also 3N – 1 , since these messages are sent sequentially.

Bully Algorithm: The bully algorithm allows processes to crash during an election, although it assumes that message delivery between processes is reliable. Unlike the ring-based algorithm, this algorithm assumes that the system is synchronous: it uses timeouts to detect a process failure. Another difference is that the ring-based algorithm assumed that processes have minimal a priori knowledge of one another: each knows only how to communicate with its neighbour and none knows the identifiers of the other processes. The bully algorithm, on the other hand, assumes that each process knows which processes have higher identifiers, and that it can communicate with all such processes.

There are three types of message in this algorithm: an election message is sent to announce an election; an answer message is sent in response to an election message and a coordinator message is sent to announce the identity of the elected process – the new ‘coordinator’. A process begins an election when it notices, through timeouts, that the coordinator has failed. Several processes may discover this concurrently.

Since the system is synchronous, we can construct a reliable failure detector. There is a maximum message transmission delay, Ttrans , and a maximum delay for processing a message Tprocess . Therefore, we can calculate a time T = 2Ttrans + Tprocess that is an upper bound on the time that can elapse

Page 16: DS_Final_Theory.docx

between sending a message to another process and receiving a response. If no response arrives within time T, then the local failure detector can report that the intended recipient of the request has failed.

The process that knows it has the highest identifier can elect itself as the coordinator simply by sending a coordinator message to all processes with lower identifiers. On the other hand, a process with a lower identifier can begin an election by sending an election message to those processes that have a higher identifier and awaiting answer messages in response. If none arrives within time T, the process considers itself the coordinator and sends a coordinator message to all processes with lower identifiers announcing this. Otherwise, the process waits a further period T’ for a coordinator message to arrive from the new coordinator. If none arrives, it begins another election.

If a process pi receives a coordinator message, it sets its variable electedi to the identifier of the coordinator contained within it and treats that process as the coordinator. If a process receives an election message, it sends back an answer message and begins another election – unless it has begun one already.

When a process is started to replace a crashed process, it begins an election. If it has the highest process identifier, then it will decide that it is the coordinator and announce this to the other processes. Thus it will become the coordinator, even though the current coordinator is functioning. It is for this reason that the algorithm is called the ‘bully’ algorithm.

Page 17: DS_Final_Theory.docx

Practical No: 07

Aim: Show the implementation of any one clock synchronization algorithm.

Problem Statement: The program contains client process and one server which host the synchronized Clocks. The client process randomly sends messages to the server. The server maintains a log of Messages and times at which they were sent. The message should finally display the messages accepted, discarded and the valid times (G) at the moment of receipt of messages.

Theory: Two clocks are said to be synchronized at a particular instance of time if the clock skew of the two clocks is less than some specified constant δ.

Every message carries a connection identifier and timestamp. For each connection, the server records in a table the most recent timestamp it has seen. In the algorithm every message carries a connection identifier (chosen by the sender) and a timestamp. For each connection, the server records in the table the most recent timestamp it has seen. If an incoming message is lower than the timestamp stored for the connection, the message is rejected. Server continuously maintains global variable,

Page 18: DS_Final_Theory.docx

G = CurrentClockTime – MaxLifeTime – MaxClockScew

Practical No: 08

Aim: Write a program to implement two phase commit protocol.

Problem Statement: Messages are passed between ‘n’ nodes (or terminals) and actions are committed or aborted, with respect to the response of other nodes. The final action is the n communicated to all other nodes.

Theory: The distributed commit problem involves having an operation being performed by each member of process group, or none at all. In the case of reliable multi-casting, the operation is the delivery of a message. With distributed transaction the operation may be committing of transaction at a single site that takes part in transaction. Distributed commit is often established by means of a co-coordinator.

In a simple scheme this co-coordinator tells all other processes that are also involves, called participants, whether or not to

Page 19: DS_Final_Theory.docx

perform the operation in question. This scheme is referred to as a one phase commit protocol. It has the obvious drawback that if one of the participants cannot actually perform the operation, there is no way to tell the coordinator. In practice, more sophisticated schemes are needed, the most common one being the two phase commit protocol. The main drawback of this protocol is that it cannot efficiently handle the failure of the coordinator.

Two Phase Commit: The original two phase commit protocol (2PC) is due to Gray(1978) without loss of generality, consider a distributed transaction involving the participation of a number of processes each running on different machines. The protocol consists of following two phases, each consisting of two steps.

The coordinator sends a VOTE_REQUEST message to all participants. When the participants receive the VOTE_REQUEST message, it returns either a VOTE_COMMIT message to the coordinator telling the coordinator that it is prepared to locally commit its part of the transaction, or otherwise a VOTE_ABORT message.

The coordinator collects the entire vote from the participants. If the participants have voted to commit the transaction, then so will the coordinator. In that case, it sends GLOBAL_COMMIT message to all other participants. However, if one participant had voted to abort the transaction the coordinator will also decide to abort the transaction and multi-casts a GLOBAL_ABORT message.

Each participant that voted for a commit waits for final reaction by the coordinator. If the participant receives the GLOBAL_COMMIT message, it locally commits the transaction. Otherwise, when receiving the GLOBAL_ABORT message the transaction is locally aborted as well.