Java EE Programming UDP TCP Javas RMI 1

  • Slides: 111
Download presentation
Java EE Programming UDP & TCP Java’s RMI 1

Java EE Programming UDP & TCP Java’s RMI 1

Topics n n n Networking and Internetworking Inter-process communication Distributed objects and remote invocation

Topics n n n Networking and Internetworking Inter-process communication Distributed objects and remote invocation UDP & TCP Java’s RMI 2

Networking Issues for Distributed Systems n Previous networks had to meet simple application requirements:

Networking Issues for Distributed Systems n Previous networks had to meet simple application requirements: n n File transfer, remote login, e-mail and newsgroups With the growth of the Internet, more stringent requirements are necessary: n n New modes of use Additional and more stringent requirements 3

Current Networking Requirements & Terms n Performance n Speed with which individual messages can

Current Networking Requirements & Terms n Performance n Speed with which individual messages can be transferred between two interconnected computers n n Latency – is the delay that occurs after a send operation is executed before data starts to arrive at the destination computer (network latency) Data transfer rate – is the speed at which data can be transferred between two computers in the network once the transmission has begun n n Bits per second Message transmission time = latency + length/data transfer rate 4

Current Networking Requirements & Terms n Scalability n The potential future size of the

Current Networking Requirements & Terms n Scalability n The potential future size of the Internet is commensurate with the population of the planet n n Indicates size and load of the Internet Networks must scale 5

Current Networking Requirements & Terms n Reliability n n The degree in which an

Current Networking Requirements & Terms n Reliability n n The degree in which an application can recover from communication failures Security n Techniques for achieving security in distributed systems n n n Firewalls – creates a protection boundary between an organization’s intranet and the rest of the Internet Distributed systems need a secure network environment with end-to-end authentication, privacy, and security Example - encryption 6

Current Networking Requirements & Terms n Mobility n n n Wireless networks provide connectivity

Current Networking Requirements & Terms n Mobility n n n Wireless networks provide connectivity to devices such as laptops, cell phones, PDAs Addressing and routing schemes of Internet were developed before the advent of wireless devices so are not well-adapted to their intermittent connection to many different subnets Quality of service n Applications that transmit multimedia data require guaranteed bandwidth and latencies 7

Current Networking Requirements & Terms n Multicasting n n One-to-many communication Needed in distributed

Current Networking Requirements & Terms n Multicasting n n One-to-many communication Needed in distributed systems 8

Types of Networks in Distributed Systems n PAN – Personal area network n n

Types of Networks in Distributed Systems n PAN – Personal area network n n Various digital devices carried by a user are connected to a low-cost, low-energy network LAN – Local area network n Carry messages at high speed between computers connected by a single communication medium n n WAN – Wide area network n n n Twisted copper wire, coaxial cable, fiber optics Carry messages a lower speeds between nodes that are often in different organizations and may be separated by large distances Uses routers to route the messages MAN – Metropolitan area network n n High speed network installed in towns/cities for transmission of data and video 9 DSL and Cable modem connections

Types of Networks in Distributed Systems n WLAN – Wireless local area network n

Types of Networks in Distributed Systems n WLAN – Wireless local area network n n n Used in place of wired LANs for wireless mobile devices IEEE 802. 11 (Wi. Fi) standard protocol WMAN – Wireless metropolitan area network n n Supercedes 802. 11 IEEE 802. 16 Wi. MAX protocol 10

Types of Networks in Distributed Systems n Internetworks – communication subsystem in which several

Types of Networks in Distributed Systems n Internetworks – communication subsystem in which several networks are linked together to provide common data communication facilities n n n Overlay the technologies and protocols of the individual component networks and methods used for their interconnection Needed for the development of extensible, open distributed systems Example – Internet 11

Network performance Example Range Bandwidth Latency (Mbps) (ms) LAN Ethernet 1 -2 kms 10

Network performance Example Range Bandwidth Latency (Mbps) (ms) LAN Ethernet 1 -2 kms 10 -1000 WAN IP routing worldwide 0. 010 -600 100 -500 MAN ATM 250 kms 1 -150 10 Internetwork Internet worldwide 0. 5 -600 100 -500 WPAN Bluetooth (802. 15. 1) 10 - 30 m 0. 5 -20 WLAN Wi. Fi (IEEE 802. 11) 0. 15 -1. 5 km 2 -54 5 -20 WMAN Wi. MAX (802. 16) 550 km 1. 5 -20 WWAN GSM, 3 G phone nets worldwide 0. 01 -02 100 -500 Wired: 1 -10 Wireless: 12

Network Protocols n n Protocol – refers to a well-known set of rules and

Network Protocols n n Protocol – refers to a well-known set of rules and formats to be used for communication between processes in order to perform a given task Two parts: n n a specification of the sequence of messages that must be exchanged a specification of the format of the data in the messages 13

Conceptual Layering of Protocol Software Message received Message sent Layer n Layer 2 Layer

Conceptual Layering of Protocol Software Message received Message sent Layer n Layer 2 Layer 1 Sender Communication medium Recipient 14

Protocol Layers n n Network software is arranged in a hierarchy of layers Each

Protocol Layers n n Network software is arranged in a hierarchy of layers Each layer presents an interface to the layers above it and below it n n Sending side – each layer (except top) accepts items of data in a specified format from the layer above it and applies transformations to encapsulate the data in the format specified for that layer Receiving side – converse transformations are applied to data items received from the layer below before being passed to layer above 15

Encapsulation as it is applied in Layered Protocols The tags in the headers are

Encapsulation as it is applied in Layered Protocols The tags in the headers are the protocol type for the layer above, needed for the receiving protocol stack to correctly unpack the packets 16

Protocol Suites n n Complete set of protocol layers is referred to as a

Protocol Suites n n Complete set of protocol layers is referred to as a protocol suite or protocol stack Reference Model for Open Systems Interconnection (OSI) Protocol layering brings substantial benefits in simplifying and generalizing the software interfaces for access to the communication services of networks Also carries significant performance costs n Why do you think this is so? 17

Protocol layers in the ISO Open Systems Interconnection (OSI) model 18

Protocol layers in the ISO Open Systems Interconnection (OSI) model 18

OSI Protocol Summary Layer Application Presentation Session Transport Network Data link Physical Description Protocols

OSI Protocol Summary Layer Application Presentation Session Transport Network Data link Physical Description Protocols that are designed to meet the communication requirements of specific applications, often defining the interface to a service. Protocols at this level transmit data in a network representation that is independent of the representations used in individual computers, which may differ. Encryption is also performed in this layer, if required. At this level reliability and adaptation are performed, such as detection of failures and automatic recovery. This is the lowest level at which messages (rather than packets) are handled. Messages are addressed to communication ports attached to processes, Protocols in this layer may be connection-oriented or connectionless. Transfers data packets between computers in a specific network. In a WAN or an internetwork this involves the generation of a route passing through routers. In a single LAN no routing is required. Responsible for transmission of packets between nodes that are directly connected by a physical link. In a WAN transmission is between pairs of routers or between routers and hosts. In a LAN it is between any pair of hosts. The circuits and hardware that drive the network. It transmits sequences of binary data by analogue signalling, using amplitude or frequency modulation of electrical signals (on cable circuits), light signals (on fibre optic circuits) or other electromagnetic signals (on radio and microwave circuits). Examples HTTP, FTP , SMTP, CORBA IIOP Secure Sockets (SSL), CORBA Data Rep. TCP, UDP IP, ATM virtual circuits Ethernet MAC, ATM cell transfer, PPP Ethernet base- band signalling, ISDN 19

Internet Protocols n TCP/IP – Transmission Control Protocol/Internet Protocol n n Grown now to

Internet Protocols n TCP/IP – Transmission Control Protocol/Internet Protocol n n Grown now to over 60 million hosts Example application services & protocols based in TCP/IP: n n n Web (HTTP) email (SMTP, POP) netnews (NNTP) file transfer (FTP) Telnet (telnet) 20

TCP/IP Layers Message Application Messages (UDP) or Streams (TCP) Transport UDP or TCP packets

TCP/IP Layers Message Application Messages (UDP) or Streams (TCP) Transport UDP or TCP packets Internet IP datagrams Network interface Network-specific frames Underlying network 21

TCP/IP Layers n Two transport protocols n n n Internet Protocol (IP) is the

TCP/IP Layers n Two transport protocols n n n Internet Protocol (IP) is the underlying ‘network’ protocol n n TCP – reliable connection-oriented protocol UDP – datagram protocol that does not guarantee reliable transmission IP datagrams provide the basic transmission mechanism for the Internet and other TCP/IP networks Internet protocols are usually layered over other network technologies n i. e, Ethernet 22

Encapsulation in a message transmitted via TCP over an Ethernet Application message TCP header

Encapsulation in a message transmitted via TCP over an Ethernet Application message TCP header port IP header TCP Ethernet header IP Ethernet frame 23

The programmer's conceptual view of a TCP/IP Internet 24

The programmer's conceptual view of a TCP/IP Internet 24

IP Addressing n Scheme chosen for naming and addressing hosts and routing IP packets

IP Addressing n Scheme chosen for naming and addressing hosts and routing IP packets to their destination n Assigns an IP address to each host in the Internet – a 32 -bit numeric identifier containing: n n network identifier – uniquely identifies one of the subnetworks in the Internet host identifier – uniquely identifies the host’s connection to that network 25

Internet Address Space Class A is reserved for very large networks (i. e. ,

Internet Address Space Class A is reserved for very large networks (i. e. , US NSFNet) Class B is used for organizations that operate networks likely to contain more than 255 computers Class C is allocated to all other network operators Class D is reserved for Internet multittask communication Class E contains a range of unallocated addresses – reserved for future use 26

TCP and UDP n n n Provide the communication capabilities of the Internet in

TCP and UDP n n n Provide the communication capabilities of the Internet in a form that is useful for application programs TCP and UDP are transport protocols and must provide process-to-process communication Accomplished by using ports Port numbers are used for addressing messages to processes within a particular computer and are only valid for that computer Once an IP packet has been delivered to its destination host, the TCP- or UDP-layer software dispatches it to a process via a specific port at that host 27

UDP Features n n n UDP datagram is encapsulated inside an IP packet Short

UDP Features n n n UDP datagram is encapsulated inside an IP packet Short header with source and destination port numbers, length field and a checksum UDP does NOT guarantee delivery n n Adds no additional reliability mechanisms except for checksum (which is optional) Use is restricted to applications and services that do not require reliable delivery of single or multiple messages 28

TCP Features n n TCP provides a much more sophisticated transport service Provides reliable

TCP Features n n TCP provides a much more sophisticated transport service Provides reliable delivery of a long sequences of bytes n n Guarantees the delivery to the receiving process of all the data presented to the TCP software by the sending process in the same order Provides retransmission if necessary n Done when the it does not receive an acknowledgement from the receiving process within a specified timeout 29

Middleware n Looking at IPC from the Programmer’s point of view n n Remote

Middleware n Looking at IPC from the Programmer’s point of view n n Remote Method Invocation (RMI) Remote Procedure Call (RPC) 30

Interprocess Communication (IPC) n Distributed Systems n rely on exchanging data and achieving synchronization

Interprocess Communication (IPC) n Distributed Systems n rely on exchanging data and achieving synchronization amongst autonomous distributed processes n Inter process communication (IPC) n n n message passing in concurrent programming languages n n n shared variables message passing language extensions API calls Principles of IPC n n (Concurrent programs: collections of two or more sequential programs executing concurrently Concurrent processes: collection of two or more sequential programs in operation, executing concurrently 31

IPC Characteristics n Message passing between pairs of processes can be supported by two

IPC Characteristics n Message passing between pairs of processes can be supported by two message communication operations: n n n send receive In order for one process to communicate with another, one process sends a message (sequence of bytes) to a destination and another process at the destination receives the message 32

Types of Communication n Synchronous n n Sending and receiving process synchronize at every

Types of Communication n Synchronous n n Sending and receiving process synchronize at every message Both send and receive are blocking operations n n Whenever a send is issued, the sending process (or thread) is blocked until the corresponding receive is issued Whenever a receive is issued, the process (or thread) blocks until a message arrives 33

Types of Communication n Asynchronous n n Send is non-blocking – sending process is

Types of Communication n Asynchronous n n Send is non-blocking – sending process is allowed to proceed as soon as the message has been copied to a local buffer Receive operation can have blocking and nonblocking variants n Non-blocking – receiving process proceeds with its program after issuing a receive operation which provides a buffer to be filled in the background n n Must separately receive notification that is buffer has been filled by polling or interrupt Today’s systems do not generally provide the nonblocking form of receive because it adds complexity to the application 34

Sockets n Both UDP and TCP use socket abstraction n Provides an endpoint for

Sockets n Both UDP and TCP use socket abstraction n Provides an endpoint for communication between processes Originated from BSD UNIX but in all Unix flavors (i. e. , Linux) IPC consists of transmitting a message between a socket in one process and a socket in another process 35

Sockets and Ports socket any port agreed port socket message client server other ports

Sockets and Ports socket any port agreed port socket message client server other ports Internet address = 138. 37. 94. 248 Internet address = 138. 37. 88. 249 36

Sockets and Ports n n n For a process to receive messages, its socket

Sockets and Ports n n n For a process to receive messages, its socket must be bound to a local port and one of the Internet addresses of the computer on which it runs Messages sent to a particular Internet address and port number can be received only by a process whose socket is associated with that Internet address and port number Processes may use the same socket for sending and receiving messages 37

Moving from Interprocess to Distributed Communication n n A distributed system breaks up a

Moving from Interprocess to Distributed Communication n n A distributed system breaks up a previously monolithic application into different components and then proceeds to place them on different systems (i. e. tiers). We are decoupling the consumer and the supplier; we are spreading the activities of an application onto team players (systems) 38

Moving from Interprocess to Distributed Communication n Analogy n n Let us imagine for

Moving from Interprocess to Distributed Communication n Analogy n n Let us imagine for a moment a small business run by a single entrepreneur. This one person, Suzette Sellers, does everything, much like a monolithic application. She sells to customers, orders new product, manages the books, pays the bills, and does anything else. Internally, she has compartmentalized her job function (much like we program in a modular fashion): selling, ordering, and administration. There is no overhead associated with external communication she does everything. When her store becomes successful, she finds that she simply cannot do it all and requires assistance. Suzette hires Henry Helpers, a capable and likeable chap. This is now similar to our two-tier architecture. Because Suzette and Henry work in the same physical location, this is a logical two-tier system. Communication is quick and easy. Think about two programs on a computer: they can communicate via files, shared memory, pipes, or other constructs. If you are familiar with processing on a UNIX- or Linix-based system, multiple commands are often strung together with pipes. 39

Moving from Interprocess to Distributed Communication n Suzette’s store does so well that she

Moving from Interprocess to Distributed Communication n Suzette’s store does so well that she moves her office into another building to increase the amount of retail floor space in her original store. Now Suzette and Henry are in different physical locations but still need to complete the same tasks of selling, ordering, and administration. We have moved into a physical two tier distributed system and things just become more complicated. Suzette and Henry still need to communicate but the previous methods will no longer work. The obvious solution is the telephone, but this changes the dynamic of the entire conversation In our computer analogy, we now have a client and a server tier where the previous solutions of files, shared memory, or pipes are no longer solutions as 40 they only work within a single system.

Moving from Interprocess to Distributed Communication n n Suzette and Henry must now specifically

Moving from Interprocess to Distributed Communication n n Suzette and Henry must now specifically locate each other (i. e. phone numbers) before communicating. Conversations will be slower (network latency). Data will need to be shared in different ways (difficult to draw a picture on the phone—the crayon keeps breaking on the handset). And finally, the phone lines can go down or have interference (network errors or corruption). 41

Moving from Interprocess to Distributed Communication n n Yes, we have gained some benefits

Moving from Interprocess to Distributed Communication n n Yes, we have gained some benefits by spreading out Suzette and Henry (more retail floor space) but we have introduced complexity and latency into the business. Similarly, when a distributed application is placed on different systems (whether physically or logically separated), we also introduce complexity and latency into the application. n n However, the ability to take advantage of multiple computers is such a powerful incentive that we have devised many ways to accommodate our new problems The stage is now set to discover how to implement this distributed communication. 42

Middleware Layer n n n By choosing Java, we are explicitly ignoring the platform

Middleware Layer n n n By choosing Java, we are explicitly ignoring the platform because Java (in theory) runs exactly the same on any platform that has a Java-compatible runtime environment. We are not yet concerned with what capabilities an application will exhibit other than we will create a “server” component that holds the desired properties and a “client” component that requests these capabilities. Assume that our distributed Java-based application will communicate via the TCP/IP protocol 43

UDP Communication n n n Basis of TCP/IP protocol stack is the Internet Protocol

UDP Communication n n n Basis of TCP/IP protocol stack is the Internet Protocol (IP) data packet IP is a connectionless and stateless protocol (“fire and forget”) Once a IP packet is sent, the sender simply does not care about it anymore IP packet can become lost, destroyed, misplaced, or corrupted on its way to its destination If multiple IP packets are sent – they can arrive out of order IP is quick to use but not reliable Think of IP as simple postal envelopes: they can be easily damaged, lost, and delivered out of order. n However, IP envelopes are cheap and convenient. (The analogy to a postal service is very appropriate as the cost is low per message and the service is usually reliable but there 44 is no capability to trace a wayward envelope. )

UDP Communication n The User Datagram Protocol (UDP) is implemented on top of IP

UDP Communication n The User Datagram Protocol (UDP) is implemented on top of IP layer. UDP is still a fairly lightweight protocol which means that most of its effort is spent on delivering data. UDP adds two important features: larger “payloads” and data integrity. n n If a message is larger than the size of a single IP envelope, UDP will split the message into multiple IP envelopes, taking care to remember how it split up the original message. UDP guarantees that the data in a single UDP packet in the will arrive exactly as it was sent. What happens if one of the IP packets that made up the UDP packet is lost? Then UDP discards the rest of the IP packets and thus the entire UDP packet rather than deliver a damaged UDP packet. This is analogous to sending a four page letter in separate envelopes; if envelope #3 does not arrive, then UDP will throw array the remaining envelopes that did arrive as it has no way to reconstruct the original four page letter. 45

UDP Communication n UDP is also a stateless and connectionless protocol n n n

UDP Communication n UDP is also a stateless and connectionless protocol n n n Stateless means that once a message is sent, the sender does not care about it anymore. If the message arrives, then that is fine. If it does not arrive, we do not feel any grief Connectionless means that there is no continued conversation. n n The message is complete in and of itself. Think about sending postcards. If we send one postcard from Europe and another from South America, neither of the postcards depend upon each other. They are separate communications 46

UDP Design Considerations n n n For client-server applications that transfer relatively small amounts

UDP Design Considerations n n n For client-server applications that transfer relatively small amounts of data, UDP is acceptable For the simplest application, a client will send a single message to the server and expect a response If the client does not receive a response within a predetermined amount of time, the client may send the request again. This is similar to asking a person to repeat an answer. Of course, after asking for the answer so many times, it is likely that we (the client) will just give up. If a DNS server does not respond after a couple of seconds, a client will simply accept that no answer is forthcoming and either ask another DNS server or return an error. 47

UDP Example n n n UDP communications can be implemented in Java quite easily

UDP Example n n n UDP communications can be implemented in Java quite easily However, it should be pointed out that UDP is simply a service to ferry data from point A to point B. UDP does not understand data types or other Java constructs, such as objects. To accommodate this understanding, we will use the capability of the String class to convert itself into an array of bytes and back. We are implicitly relying on the String class to correctly convert an array of bytes using the correct code set. Both the server and client will perform many of the same operations but the server has the additional task of existing in a state where it can receive requests at any time and must respond to them. A client, on the other hand, will only be executed on demand exit as soon as it receives a response. 48

UDP Server n n n The UDP server may look complicated but there is

UDP Server n n n The UDP server may look complicated but there is actually very little to it. The server first creates a socket, which is a logical construct that we may attach to an actual port. We have hard-coded the port upon which our server will listen, 7777. n n You may choose any port between 1024 and 65535 (assuming that it is not already in use). The server attaches to the port and then performs an endless loop of listening for any incoming message and sending the same message (known as a datagram) back to its sender. The effect is similar to a mirror See UDPServer. Simple. java 49

UDP Client n The UDP client seems to be much longer in length but

UDP Client n The UDP client seems to be much longer in length but that is because we have added in the ability to specify the message to send, the server name, and the port on which the UDP server is listening on the command line, rather than hard-coding it. n n n This approach should allow you to run the program as-is, even though you will run it on your system (which has a different network name and IP address than everybody else’s system). The client, similar to the server, first creates a socket that can be bound to a network port. However, we will not bind it to a particular port because we do not care—just as when you send a letter, the mailbox you use is irrelevant to the receiver. 50

UDP Client n n n The client program then resolves the name of the

UDP Client n n n The client program then resolves the name of the server (first argument) to an IP address, which is what the UDP protocol requires. The second argument is the port that the UDP server is listening on, and the third argument is the actual message (remember to enclose it in double quotes if it contains a space). A datagram message is then created and sent to the server. Immediately after sending the message, the client then acts like the server, waiting for a reply. Although the client did not request a specific port, the port that was automatically assigned is included in the outgoing message so that the server can successfully respond back to us. See UDPClient. Simple. java 51

UDP Example In Action n We first start the UDP server which opens the

UDP Example In Action n We first start the UDP server which opens the port and waits for the first incoming message. It will wait until the program is terminated Although not shown, the UDP server is running on a system with the name “Alpha” (as in the first Greek letter). 52

UDP Example In Action n n The server gets up and running quickly and

UDP Example In Action n n The server gets up and running quickly and then immediately starts waiting for eternity Then run the UDP client which sends a message and then itself waits for a reply. 53

UDP Example In Action n n Notice that the client runs and then exits.

UDP Example In Action n n Notice that the client runs and then exits. This is typical of most client-server communications where the client makes a request, receives a reply from the server and is done. 54

UDP Example In Action n Meanwhile, the server has recorded the incoming message, responded

UDP Example In Action n Meanwhile, the server has recorded the incoming message, responded to it, and begun waiting for another incoming request. 55

TCP Communication n n TCP network communication is similar to UDP but it “fixes”

TCP Communication n n TCP network communication is similar to UDP but it “fixes” the flaws inherent in UDP by providing message delivery guarantee and concurrency. TCP goes a step beyond UDP and is a stateful and connection-oriented protocol. n n Stateful means that the TCP remembers what it has sent and ensures that it arrives in the same order Connection-oriented means that each packet sent is actually part of a larger conversation, or stream. 56

TCP Communication n A TCP-based server differs from a UDP-based server in that a

TCP Communication n A TCP-based server differs from a UDP-based server in that a single thread does not perform all of the communication. The usual solution to handle TCP communications is to create a new thread that is dedicated to incoming requests from a particular client. A server can distinguish multiple requests from the multiple clients on the same client system because each client will be forced to use a different port 57

TCP Example n n The programs for the TCP client and server are similar

TCP Example n n The programs for the TCP client and server are similar in nature although the details vary a bit. Because TCP is stateful, we actually open up two streams: one inbound and one outbound These act like conveyor belts for data to flow between the client and the server. From a programming standpoint, we no longer have to use datagrams but can simply read and write a simple data type or a string object. 58

TCP Server n n n For the server, the largest change is that additional

TCP Server n n n For the server, the largest change is that additional of threads in order to maintain each connection as a separate conversation. However, once inside of a thread, the commands are simply reading and writing data. See TCPServer. java 59

TCP Client n n n The TCP client is very similar to the UDP

TCP Client n n n The TCP client is very similar to the UDP client except that instead of sending datagrams, we hook up to the streamsbased plumbing. However, the rest of the logic is pretty much the same. See TCPClient. java 60

TCP Example in Action n n Set CLASSPATH first! Start with the server first

TCP Example in Action n n Set CLASSPATH first! Start with the server first 61

TCP Example in Action n n Next we invoke the TCP client to send

TCP Example in Action n n Next we invoke the TCP client to send a simple message. We can see that the client was able to acquire a port to communicate out and received a reply that was different than what was originally sent, proving that “something” happened. 62

TCP Example in Action n The server first received a connection from the remote

TCP Example in Action n The server first received a connection from the remote port of 4304 (the client). It then created new client. Connection object (the two lines with the word setup in the brackets) and then went back to listening for more connection requests. Meanwhile, the new thread was run and it picked up the message sent by the client and then sent it back with the prefix “Received: ”. 63

Remote Method Invocation (RMI) n n n Provides for communication between distributed objects by

Remote Method Invocation (RMI) n n n Provides for communication between distributed objects by means of remote method invocation RMI = objects that can receive remote method invocations are called remote objects and they implement a remote interface Is an extension of local method invocation that allows an object living in one process to invoke methods of an object living in another process 64

Middleware Layer for RMI Applications RMI, RPC and events Request reply protocol Middleware layers

Middleware Layer for RMI Applications RMI, RPC and events Request reply protocol Middleware layers External data representation Operating System 65

Interfaces in Distributed Systems n n An interface specifies the procedures and variables that

Interfaces in Distributed Systems n n An interface specifies the procedures and variables that can be accessed from other modules Modules are implemented so as to hide all the information about them except that which is available through its interface. As long as the interface does NOT change, implementations may change without affecting the users of the module In a distributed program, the modules can run in separate processes. n Cannot access the variables in a module in another process – not direct variable access 66

Interfaces in Distributed Systems n Other differences: n Parameter-passing mechanisms (i. e. , call

Interfaces in Distributed Systems n Other differences: n Parameter-passing mechanisms (i. e. , call by value, call by reference) used in local procedure calls do not work in a distributed system n n Uses input and output parameters that are passed between processes Pointers in one process are not valid in another process on a remote computer n No pointer passing allowed 67

Remote and Local Method Invocations local remote invocation A B C local E invocation

Remote and Local Method Invocations local remote invocation A B C local E invocation local invocation D remote invocation F 68

Java RMI n n n Java RMI provides an adapter that effectively hides the

Java RMI n n n Java RMI provides an adapter that effectively hides the network from us, instead allowing us to simply “lookup” functionality that we want (regardless of where it actually exists) and use it as if it was locally available. The level of complexity definitely increases once we decide to distribute the objects in a Java system. Assuming that we started with two Java programs, with one calling the other, we now introduce the following elements: n n n an interface that explicitly states what functionality is remotely available a server that provides access to the remote object the RMI registry that links up requests from a client to a remote object 69

Overview of RMI Interfaces and Classes 70

Overview of RMI Interfaces and Classes 70

Java RMI Example Foundation n n We will start with two Java classes that

Java RMI Example Foundation n n We will start with two Java classes that are not RMI-enabled and then adapt them to operate with RMI so we can see exactly what changes are needed. Let us imagine that we have devised an automated registration process class which, upon knowing which class for which we want to register, will tell us if we are registered or if the class is full. 71

Ask. The. Registrar. java public class Ask. The. Registrar { private String the. Class;

Ask. The. Registrar. java public class Ask. The. Registrar { private String the. Class; public Ask. The. Registrar ( String in_which. Class ) { the. Class = in_which. Class; } public String get. Registration. Status() { if ( the. Class. to. Upper. Case(). index. Of( "CS 483" ) >= 0 ) { return "You are registered"; } else { return "There are no positions available to be registered"; } } } If the class includes the word “CS 483” (case sensitive) then the class must have some spots open. Otherwise, the class is full. 72

Java Application to Invoke the Functionality – Local. Student. java class Local. Student {

Java Application to Invoke the Functionality – Local. Student. java class Local. Student { public static void main( String args[] ) { System. out. println(); System. out. println( "Local. Student running. . . " ); System. out. println( "-------------" ); System. out. println(); String student. Class; In order to work, both classes if ( args. length < 1 ) just need to be in a directory within { the current CLASSPATH student. Class = "CS 483"; } environment variable else { student. Class = args[0]; } Ask. The. Registrar current. Registration. Status = new Ask. The. Registrar(student. Class); System. out. println( "The registration status for " + student. Class + " is: "); System. out. println(" > “ + current. Registration. Status. get. Registration. Status()); System. out. println( "-------------" ); 73 System. out. println( "Local. Student finished. " ); }

Result when run. . . n By passing the argument “CS 483”, the Ask.

Result when run. . . n By passing the argument “CS 483”, the Ask. The. Registrar service concludes that the student is registered 74

Java RMI Example (with a server) n n We now seek to move the

Java RMI Example (with a server) n n We now seek to move the Ask. The. Registrar service to a remote server so that it can be accessed from multiple locations within the university. The first step is to decide what functionality should be made available. n n Currently, the Ask. The. Registrar class has two member functions: the constructor and get. Registration. Status. The constructor will not be available remotely and so we need to create an alternative method to set the location. These two functions, set. Class and get. Registration. Status, will be available to remote invocation and we can now create an interface detailing this decision. Need to enhance the object Ask. The. Registrar so that it can be remotely used 75

RMI Server Example – Sequence Diagram 76

RMI Server Example – Sequence Diagram 76

Ask. The. Registrar. Interface. java import java. rmi. *; public interface Ask. The. Registrar.

Ask. The. Registrar. Interface. java import java. rmi. *; public interface Ask. The. Registrar. Interface extends Remote { public void set. Class( String in_which. Class ) throws Remote. Exception; public String get. Registration. Status( ) throws Remote. Exception; } *Remember an interface is a contract that a class can choose to implement so there is no actual code in the interface itself 77

New Version of Ask. The. Registrar n n n See Ask. The. Registrar. Remote.

New Version of Ask. The. Registrar n n n See Ask. The. Registrar. Remote. java Imported java. rmi and java. rmi. server packages to enable remote invocation capability Class inherits from the Unicase. Remote. Object parent class n n n This object means that a single instance (as opposed to one instance per request) of the Ask. Remote. Registrar. Remote object will be enabled to be called remotely Provides methods outlined in the interface Added an additional constructor that takes no arguments and sets the private the. Class variable 78

RMI Registry n n A client wishing to use a remote object will need

RMI Registry n n A client wishing to use a remote object will need to know exactly where it is located RMI registry n n n Coordinated “phone book” that records every object’s name and address Publishes object’s info in a well-known location rmiregistry. exe n n n In the same directory as other java executables Can be run by itself as a background process We will run in it’s own command window 79

RMI Registry n n n RMI Registry starts off with an empty directory Has

RMI Registry n n n RMI Registry starts off with an empty directory Has no way of actually invoking any objects It’s only job is to provide locations to any program that asks (like directory assistance) 80

RMI Server Example n n We now need a Java program similar to our

RMI Server Example n n We now need a Java program similar to our UDP server that accepts requests for a remote object This server program must also communicate to the RMI registry that it exists so clients can find it 81

Ask. The. Registrar. Server. java import java. rmi. *; import java. rmi. server. *;

Ask. The. Registrar. Server. java import java. rmi. *; import java. rmi. server. *; class Ask. The. Registrar. Server { public static void main ( String[] args ) { try { Naming. rebind("//localhost/Ask. The. Registrar", new Ask. The. Registrar. Remote()); System. out. println("Ask. The. Registrar Server is ready. "); System. out. println(); } catch (Exception e) { System. out. println("Ask. The. Registrar Server unexpectedly quit. “ +"Exception message: " + e. get. Message()); } //end try } //end main } //end class 82

RMI Server Example n n This seems like a very small amount of code

RMI Server Example n n This seems like a very small amount of code compared to our previous UDP server. The magic happens on a single line: . . . Naming. rebind( "//localhost/Ask. The. Registrar", new Ask. The. Registrar. Remote() ); . . . 83

RMI Server Example n n The rebind command is what actually informs the RMI

RMI Server Example n n The rebind command is what actually informs the RMI registry that a remote object is now available for remote invocation. The first argument is the remote object’s name in the directory as well as which RMI registry will be informed. n n n In our example, we are contacting the registry on the local server (i. e. localhost). If the registry was on a port other than its default 1098, this could be specified by placing a colon and the new port number directly after the server name. The identifier after the server is the name that the object will be listed as in the registry. n This directory name does not have to be the same as the 84 actual remote object.

RMI Server Example n The second argument creates the actual remote object that will

RMI Server Example n The second argument creates the actual remote object that will accept requests from clients. n n n Because we are unsure of what location a client will specify, we invoke the no-argument version of the constructor which will set the internal location to an empty string (and thus require the client to specify an actual location later). Most important point to heed is that in our non-RMI setup (previous example), each instance of the client application (Location. Student) created its own instance of the Ask. The. Registrar service class. In the RMI version, we have a single instance of the Ask. The. Registrar class that will be used by and all clients. 85

RMI Server Example n n Before we can run the server, we need to

RMI Server Example n n Before we can run the server, we need to generate a “stub” class for the remote object that will be used by the server. We use the rmic utility to do this. Server does not exit – RMI registry still has an open reference to it – continuously available to any incoming requests Now that we have a server, we run it from the command line like so: 86

Client Example n n Create a client that accesses the Ask. The. Registrar remote

Client Example n n Create a client that accesses the Ask. The. Registrar remote object Two critical lines: . . . Ask. The. Registrar. Interface the. Registrar = (Ask. The. Registrar. Interface) Naming. lookup ( "//" + remote. Server + "/Ask. The. Registrar" ); . . . System. out. println( " > " + the. Registrar. get. Registration. Status()); . . . 87

Client Example n n n The first uses the same class, Naming, that the

Client Example n n n The first uses the same class, Naming, that the server did to contact the RMI registry. In this case, we are asking the registry for the location of a remote object that should be known as “Ask. The. Registrar”. n Note that what is returned is a reference to the interface we initially created. n This interface hides the fact that there is no code locally but simply provides some stubs that will make a call to the remote object to perform the actual work. The second line uses the resulting object reference as if it were local— which was our original intent . . . Ask. The. Registrar. Interface the. Registrar = (Ask. The. Registrar. Interface) Naming. lookup ( "//" + remote. Server + "/Ask. The. Registrar" ); . . . System. out. println( " > " + the. Registrar. get. Registration. Status()); . . . 88

Client Example n We can now see the result of running the client: 89

Client Example n We can now see the result of running the client: 89

Server Output n This is the activity on the server: n Server displays the

Server Output n This is the activity on the server: n Server displays the caller’s (client) IP address 90

Java RMI Example (with a daemon) n n n The previous example requires us

Java RMI Example (with a daemon) n n n The previous example requires us to run a separate Java application in a server capacity to register and make a remote object available. If we wish to make multiple objects available as remote objects, we will either need to run a separate server for each or create “super-server” that registers one of each object. To solve this problem use the RMI daemon (background process), or rmid. This one process will replace all of the other server processes and allow any remote object to be dynamically invoked No adjustments to the interface or the client code are 91 required.

Java RMI with the Daemon Sequence Diagram 92

Java RMI with the Daemon Sequence Diagram 92

Java RMI Example (with a daemon) n n The remote object that we created

Java RMI Example (with a daemon) n n The remote object that we created in Ask. The. Registrar. Remote last time needs to be modified to inherit from a different, but related object—the Activatable object (which implies that the remote object may be “activated” on demand). For clarity, we will rename the class Ask. The. Registrar. Remote to Ask. The. Registrar. Activation. 93

import public java. rmi. *; java. rmi. server. *; Ask. The. Registrar. Activation. java.

import public java. rmi. *; java. rmi. server. *; Ask. The. Registrar. Activation. java. rmi. activation. *; class Ask. The. Registrar. Activation extends Activatable implements Ask. The. Registrar. Interface { private String the. Class; // + This constructor (which was not required when // we used the server-based form of RMI) will // be automatically called by the RMI daemon. // public Ask. The. Registrar. Activation( Activation. ID id, Marshalled. Object data ) throws Remote. Exception { // + Register the object with the activation system // then export it on an anonymous port // super(id, 0); // + Here is our additional code. the. Class = "(No class set)"; }. . . } 94

Java RMI Example (with a daemon) n n Instead of inheriting from Unicast. Remote.

Java RMI Example (with a daemon) n n Instead of inheriting from Unicast. Remote. Object, the remote object now inherits from Activatable. Both of the constructors that previously existed have been removed and replaced with one that has two arguments – Activation ID & Marshalled. Object n n Any initialization code we need is placed after the parent constructor is called. Other than those changes, the code for the remote object is the same. What has changed the most is that instead of a server process, we only need to register the object as available for remote invocation and then create a stub for use with the new daemon process. 95

Java RMI Example (with a daemon) Server Application n n See Ask. The. Registrar.

Java RMI Example (with a daemon) Server Application n n See Ask. The. Registrar. RMIDSetup. java The server application has undergone some dramatic change. The first statement inside the main class provides the first hint of the alterations. We are now operating with enhanced security restrictions that we will need to alter in order for our remote object to accept any connections (a remote object that communicates with nobody is not very useful). 96

Java RMI Example (with a daemon) Server Application n To accomplish these alterations, we

Java RMI Example (with a daemon) Server Application n To accomplish these alterations, we need a security manager to be available like so: . . . System. set. Security. Manager( new RMISecurity. Manager()); . . . 97

Java RMI Example (with a daemon) Server Application n n Next, we need to

Java RMI Example (with a daemon) Server Application n n Next, we need to associate a security policy file with the remote object when it is activated. The policy file simply states that the remote object is allowed to accept connections via the network from any address as long as the originating port is unprivileged (i. e. above 1023). n It should be noted that although the policy file kind of looks like Java code, it is a configuration file and not compiled; it remains a text file called Ask. The. Registrar. Activation. policy grant { // + This allows the remote Ask. The. Registrar object to accept // incoming connections from anywhere, as long as it is on // an unprivileged port (which is normally the case). // permission java. net. Socket. Permission "*: 1024 -", "accept"; }; 98

Java RMI Example (with a daemon) n n n The RMI registry is still

Java RMI Example (with a daemon) n n n The RMI registry is still operating as it was previously therefore it must be run first of all the server-based processes. The RMI daemon must be run next. However, it will default to being very restrictive with any of the remote objects that will be registered with it as available to be activated. So, we must define a security policy for the RMI daemon itself that allows future remote objects to be allowed to register their own security policy. This could potentially open the door for arbitrary permissions which is why this step is explicitly required. 99

Java RMI Example (with a daemon) n n Our security policy will look like

Java RMI Example (with a daemon) n n Our security policy will look like the following: RMID. policy This policy has only one purpose: future remote objects that will be registered may use the security policy located in a file Z: CS 483Ask. The. Registrar. Activation. policy. Any other request for elevated permissions will be expressly denied. grant { // + This allows the remote Ask. The. Registrar object to // request the security policy in the file // Z: CS 483Ask. The. Registrar. policy. // + If this is not allowed, then the remote Ask. The. Registrar // object will either not be allowed to registered, or // will be registered with no ability to make network // connections. // permission com. sun. rmid. Exec. Option. Permission "Djava. security. policy=Z: /CS 483/Ask. The. Registrar. Activation. policy"; }; 100

Run the daemon n By default, the RMI daemon uses a security policy of

Run the daemon n By default, the RMI daemon uses a security policy of “none” (which is like selling a padlock with no key) so we must change this when running the daemon process. C: > %JAVAHOME%rmid –J-Djava. security. policy=RMID. policy n Start the daemon: 101

Java RMI Example (with a daemon) n n n Next, we must register the

Java RMI Example (with a daemon) n n n Next, we must register the Ask. The. Registrar remote object with the daemon and registry. The registration program itself needs permission to contact both the daemon and the registry. Here is its policy file: grant { // + This allows the Ask. The. Registrar setup to connect to // the RMI registry. // permission java. net. Socket. Permission "Alpha: 1098", "connect"; // + This allows the Ask. The. Registrar setup to connect to // the RMI daemon (background process). // permission java. net. Socket. Permission "Alpha: 1099", "connect"; }; 102

Java RMI Example (with a daemon) n n Assuming that the remote Ask. The.

Java RMI Example (with a daemon) n n Assuming that the remote Ask. The. Registrar object will reside on the server known as “Alpha”, the policy file allows the setup program to contact the registry on the default port 1098 and the daemon on the default port of 1099 If the registration succeeds like we sincerely hope it will, we should get two status messages: C: > java -Djava. security. policy=Ask. The. Registrar. RMIDSetup. policy Ask. The. Registrar. RMIDSetup 103

Java RMI Example (with a daemon) n n It is worthwhile to note here

Java RMI Example (with a daemon) n n It is worthwhile to note here that the remote object, Ask. The. Registrar. Activation, has not yet been instantiated and will remain so until the first request. This is one of the main benefits of the daemon implementation in that it conserves resources until they are required. 104

Java RMI Example (with a daemon) n We need to make two more adjustments.

Java RMI Example (with a daemon) n We need to make two more adjustments. n n First, we need to provide the client with a “stub” copy of the remote object (in addition to the compiled interface definition). After compiling the remote object (which is Ask. The. Registrar. Activation in our example), we employ the remote invocation compiler to whittle it down to just a stub. C: > %JAVAHOME%rmic Ask. The. Registrar. Activation 105

Java RMI Example (with a daemon) n n This will produce a file named

Java RMI Example (with a daemon) n n This will produce a file named Ask. The. Registrar. Activation_stub. class that needs to be distributed with the client application (in addition to the Ask. The. Registrar. Interface. class and Local. Student. Client. class files). Secondly, while the client is unchanged, it now requires a security policy file in order to access the RMI daemon and registry grant { // + This allows the local client permission to use the network // and make outbound connections to the "Alpha" server on any // unprivileged port. // permission java. net. Socket. Permission "Alpha: 1024 -", "connect, resolve"; }; 106

Java RMI Example (with a daemon) n n The policy file for the client

Java RMI Example (with a daemon) n n The policy file for the client says that connections may be made to any non-privileged port on the server that contains the remote object. When executing the client application, we now need to include a reference to the security policy file. C: > java Djava. security. policy=Local. Student. Clien t. policy Local. Student. Client Alpha "CS 483" 107

Executed Client Application with Reference to Policy File 108

Executed Client Application with Reference to Policy File 108

Local. Student Client n n n Our invocation of a remote object is now

Local. Student Client n n n Our invocation of a remote object is now functional again! That was certainly a lot of work just to learn that we are registered for CS 483. If we look back at the RMI daemon, we note that the status messages are displayed, with some extra logging information about execution groups (which we did not cover). 109

RMI Daemon n Again, the benefit to this setup is that we can run

RMI Daemon n Again, the benefit to this setup is that we can run with just the daemon and dynamically register objects with the daemon and the object will be immediately available for use by clients. 110

Java RMI Resources n n http: //java. sun. com/docs/books/tutori al/rmi/index. html http: //java. sun.

Java RMI Resources n n http: //java. sun. com/docs/books/tutori al/rmi/index. html http: //java. sun. com/j 2 se/1. 5. 0/docs/g uide/rmi/spec/rmi. TOC. html http: //java. sun. com/j 2 se/1. 5. 0/docs/t ooldocs/windows/rmic. html 111