111
1 Java EE Programming UDP & TCP Java’s RMI

Java EE Programming

  • Upload
    gram

  • View
    57

  • Download
    1

Embed Size (px)

DESCRIPTION

Java EE Programming . UDP & TCP Java’s RMI. Topics . Networking and Internetworking Inter-process communication Distributed objects and remote invocation UDP & TCP Java’s RMI. Networking Issues for Distributed Systems. Previous networks had to meet simple application requirements: - PowerPoint PPT Presentation

Citation preview

Page 1: Java EE Programming

1

Java EE Programming

UDP & TCPJava’s RMI

Page 2: Java EE Programming

2

Topics

Networking and Internetworking Inter-process communication Distributed objects and remote

invocation UDP & TCP Java’s RMI

Page 3: Java EE Programming

3

Networking Issues for Distributed Systems

Previous networks had to meet simple application requirements: File transfer, remote login, e-mail and

newsgroups With the growth of the Internet, more

stringent requirements are necessary: New modes of use Additional and more stringent

requirements

Page 4: Java EE Programming

4

Current Networking Requirements & Terms Performance

Speed with which individual messages can be transferred between two interconnected computers

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

Bits per second Message transmission time =

latency + length/data transfer rate

Page 5: Java EE Programming

5

Current Networking Requirements & Terms

Scalability The potential future size of the Internet

is commensurate with the population of the planet

Indicates size and load of the Internet Networks must scale

Page 6: Java EE Programming

6

Current Networking Requirements & Terms Reliability

The degree in which an application can recover from communication failures

Security Techniques for achieving security in

distributed systems 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

Page 7: Java EE Programming

7

Current Networking Requirements & Terms Mobility

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 Applications that transmit multimedia data

require guaranteed bandwidth and latencies

Page 8: Java EE Programming

8

Current Networking Requirements & Terms

Multicasting One-to-many communication Needed in distributed systems

Page 9: Java EE Programming

9

Types of Networks in Distributed Systems PAN – Personal area network

Various digital devices carried by a user are connected to a low-cost, low-energy network

LAN – Local area network Carry messages at high speed between computers

connected by a single communication medium Twisted copper wire, coaxial cable, fiber optics

WAN – Wide area network 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

High speed network installed in towns/cities for transmission of data and video

DSL and Cable modem connections

Page 10: Java EE Programming

10

Types of Networks in Distributed Systems

WLAN – Wireless local area network Used in place of wired LANs for

wireless mobile devices IEEE 802.11 (WiFi) standard protocol

WMAN – Wireless metropolitan area network Supercedes 802.11 IEEE 802.16 WiMAX protocol

Page 11: Java EE Programming

11

Types of Networks in Distributed Systems Internetworks – communication

subsystem in which several networks are linked together to provide common data communication facilities 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

Page 12: Java EE Programming

Network performanceExample Range Bandwidth

(Mbps)Latency(ms)

Wired:

LAN Ethernet 1-2 kms 10-1000 1-10

WAN IP routing worldwide 0.010-600 100-500

MAN ATM 250 kms 1-150 10

Internetwork Internet worldwide 0.5-600 100-500

Wireless:

WPAN Bluetooth (802.15.1) 10 - 30m 0.5-2 5-20

WLAN WiFi (IEEE 802.11) 0.15-1.5 km 2-54 5-20

WMAN WiMAX (802.16) 550 km 1.5-20 5-20

WWAN GSM, 3G phone nets worldwide 0.01-02 100-500

Page 13: Java EE Programming

13

Network Protocols 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: a specification of the sequence of

messages that must be exchanged a specification of the format of the data

in the messages

Page 14: Java EE Programming

14

Conceptual Layering of Protocol Software

Layer n

Layer 2

Layer 1

Message sent Message received

Communicationmedium

Sender Recipient

Page 15: Java EE Programming

15

Protocol Layers Network software is arranged in a

hierarchy of layers Each layer presents an interface to the

layers above it and below it 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

Page 16: Java EE Programming

16

Encapsulation as it is applied in Layered Protocols

Presentation header

Application-layer message

Session header

Transport header

Network header

The tags in the headers are the protocol type for the layer above, needed for the receiving protocol stack to correctly unpack the packets

Page 17: Java EE Programming

17

Protocol Suites 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 Why do you think this is so?

Page 18: Java EE Programming

18

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

Application

Presentation

Session

Transport

Network

Data link

Physical

Message sent Message received

Sender Recipient

Layers

Communicationmedium

Page 19: Java EE Programming

19

OSI Protocol SummaryLayer Description ExamplesApplication Protocols that are designed to meet the communication requirements of

specific applications, often defining the interface to a service. HTTP, FTP , SMTP,CORBA IIOP

Presentation Protocols at this level transmit data in a network representation that isindependent of the representations used in individual computers, which maydiffer. Encryption is also performed in this layer, if required.

Secure Sockets(SSL),CORBA DataRep.

Session At this level reliability and adaptation are performed, such as detection offailures and automatic recovery.

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

TCP, UDP

Network Transfers data packets between computers in a specific network. In a WANor an internetwork this involves the generation of a route passing throughrouters. In a single LAN no routing is required.

IP, ATM virtualcircuits

Data link Responsible for transmission of packets between nodes that are directlyconnected by a physical link. In a WAN transmission is between pairs ofrouters or between routers and hosts. In a LAN it is between any pair of hosts.

Ethernet MAC,ATM cell transfer,PPP

Physical The circuits and hardware that drive the network. It transmits sequences ofbinary data by analogue signalling, using amplitude or frequency modulationof electrical signals (on cable circuits), light signals (on fibre optic circuits)or other electromagnetic signals (on radio and microwave circuits).

Ethernet base- bandsignalling, ISDN

Page 20: Java EE Programming

20

Internet Protocols TCP/IP – Transmission Control

Protocol/Internet Protocol Grown now to over 60 million hosts

Example application services & protocols based in TCP/IP: Web (HTTP) email (SMTP, POP) netnews (NNTP) file transfer (FTP) Telnet (telnet)

Page 21: Java EE Programming

21

TCP/IP Layers

Messages (UDP) or Streams (TCP)

Application

Transport

Internet

UDP or TCP packets

IP datagrams

Network-specific frames

MessageLayers

Underlying network

Network interface

Page 22: Java EE Programming

22

TCP/IP Layers Two transport protocols

TCP – reliable connection-oriented protocol UDP – datagram protocol that does not

guarantee reliable transmission Internet Protocol (IP) is the underlying

‘network’ protocol IP datagrams provide the basic transmission

mechanism for the Internet and other TCP/IP networks

Internet protocols are usually layered over other network technologies i.e, Ethernet

Page 23: Java EE Programming

23

Encapsulation in a message transmitted via TCP over an Ethernet

Application message

TCP header

IP header

Ethernet header

Ethernet frame

port

TCP

IP

Page 24: Java EE Programming

24

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

IP

Application Application

TCP UDP

Page 25: Java EE Programming

25

IP Addressing Scheme chosen for naming and

addressing hosts and routing IP packets to their destination Assigns an IP address to each host in

the Internet – a 32-bit numeric identifier containing:

network identifier – uniquely identifies one of the subnetworks in the Internet

host identifier – uniquely identifies the host’s connection to that network

Page 26: Java EE Programming

Internet Address Space7 24

Class A: 0 Network ID Host ID

14 16

Class B: 1 0 Network ID Host ID

21 8

Class C: 1 1 0 Network ID Host ID

28

Class D (multicast): 1 1 1 0 Multicast address

27

Class E (reserved): 1 1 1 1 unused0

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 computersClass C is allocated to all other network operatorsClass D is reserved for Internet multittask communicationClass E contains a range of unallocated addresses – reserved for future use

Page 27: Java EE Programming

27

TCP and UDP 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

Page 28: Java EE Programming

28

UDP Features 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

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

Page 29: Java EE Programming

29

TCP Features TCP provides a much more

sophisticated transport service Provides reliable delivery of a long

sequences of bytes 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 Done when the it does not receive an

acknowledgement from the receiving process within a specified timeout

Page 30: Java EE Programming

30

Middleware

Looking at IPC from the Programmer’s point of view

Remote Method Invocation (RMI) Remote Procedure Call (RPC)

Applications, services

Middlewarelayers

request-reply protocol

marshalling and external data representation

UDP and TCP

Thischapter

RMI and RPC

Page 31: Java EE Programming

31

Interprocess Communication(IPC)

Distributed Systems rely on exchanging data and achieving

synchronization amongst autonomous distributed processes

Inter process communication (IPC) shared variables message passing

message passing in concurrent programming languages language extensions API calls

Principles of IPC (Concurrent programs: collections of two or more

sequential programs executing concurrently Concurrent processes: collection of two or more

sequential programs in operation, executing concurrently

Page 32: Java EE Programming

32

IPC Characteristics Message passing between pairs of

processes can be supported by two message communication operations: 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

Page 33: Java EE Programming

33

Types of Communication Synchronous

Sending and receiving process synchronize at every message

Both send and receive are blocking operations

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

Page 34: Java EE Programming

34

Types of Communication Asynchronous

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 non-blocking variants

Non-blocking – receiving process proceeds with its program after issuing a receive operation which provides a buffer to be filled in the background

Must separately receive notification that is buffer has been filled by polling or interrupt

Today’s systems do not generally provide the non-blocking form of receive because it adds complexity to the application

Page 35: Java EE Programming

35

Sockets Both UDP and TCP use socket

abstraction 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

Page 36: Java EE Programming

36

message

agreed portany port socketsocket

Internet address = 138.37.88.249Internet address = 138.37.94.248

other ports

client server

Sockets and Ports

Page 37: Java EE Programming

37

Sockets and Ports 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

Page 38: Java EE Programming

38

Moving from Interprocess to Distributed Communication

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)

Page 39: Java EE Programming

39

Moving from Interprocess to Distributed Communication Analogy

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.

Page 40: Java EE Programming

40

Moving from Interprocess to Distributed Communication

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 they only work within a single system.

Page 41: Java EE Programming

41

Moving from Interprocess to Distributed Communication

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

Page 42: Java EE Programming

42

Moving from Interprocess to Distributed Communication 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.

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.

Page 43: Java EE Programming

43

Middleware Layer 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

Page 44: Java EE Programming

44

UDP Communication 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. 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 is no capability to trace a wayward envelope.)

Page 45: Java EE Programming

45

UDP Communication 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. 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.

Page 46: Java EE Programming

46

UDP Communication UDP is also a stateless and

connectionless protocol 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.

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

Page 47: Java EE Programming

47

UDP Design Considerations

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 pre-determined 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.

Page 48: Java EE Programming

48

UDP Example 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 and exit as soon as it receives a response.

Page 49: Java EE Programming

49

UDP Server 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. 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 UDPServerSimple.java

Page 50: Java EE Programming

50

UDP Client 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.

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.

Page 51: Java EE Programming

51

UDP Client 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 UDPClientSimple.java

Page 52: Java EE Programming

52

UDP Example In Action 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).

Page 53: Java EE Programming

53

UDP Example In Action

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.

Page 54: Java EE Programming

54

UDP Example In Action

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.

Page 55: Java EE Programming

55

UDP Example In Action

Meanwhile, the server has recorded the incoming message, responded to it, and begun waiting for another incoming request.

Page 56: Java EE Programming

56

TCP Communication 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. 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.

Page 57: Java EE Programming

57

TCP Communication 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

Page 58: Java EE Programming

58

TCP Example 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.

Page 59: Java EE Programming

59

TCP Server 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

Page 60: Java EE Programming

60

TCP Client The TCP client is very similar to the

UDP client except that instead of sending datagrams, we hook up to the streams-based plumbing.

However, the rest of the logic is pretty much the same.

See TCPClient.java

Page 61: Java EE Programming

61

TCP Example in Action

Set CLASSPATH first! Start with the server first

Page 62: Java EE Programming

62

TCP Example in Action

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.

Page 63: Java EE Programming

63

TCP Example in Action

The server first received a connection from the remote port of 4304 (the client).

It then created new clientConnection 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:”.

Page 64: Java EE Programming

64

Remote Method Invocation (RMI)

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

Page 65: Java EE Programming

65

Middleware Layer for RMI

Applications

Middlewarelayers Request reply protocol

External data representation

Operating System

RMI, RPC and events

Page 66: Java EE Programming

66

Interfaces in Distributed Systems

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. Cannot access the variables in a module in

another process – not direct variable access

Page 67: Java EE Programming

67

Interfaces in Distributed Systems

Other differences: Parameter-passing mechanisms (i.e.,

call by value, call by reference) used in local procedure calls do not work in a distributed system

Uses input and output parameters that are passed between processes

Pointers in one process are not valid in another process on a remote computer

No pointer passing allowed

Page 68: Java EE Programming

68

Remote and Local Method Invocations

invocation invocationremote

invocationremote

locallocal

localinvocation

invocationA B

C

D

E

F

Page 69: Java EE Programming

69

Java RMI 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:

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

Page 70: Java EE Programming

70

Overview of RMI Interfaces and Classes

Page 71: Java EE Programming

71

Java RMI Example Foundation

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.

Page 72: Java EE Programming

public class AskTheRegistrar{ private String theClass; public AskTheRegistrar ( String in_whichClass ) { theClass = in_whichClass; } public String getRegistrationStatus() { if ( theClass.toUpperCase().indexOf( "CS483" ) >= 0 ) { return "You are registered"; } else { return "There are no positions available to be registered"; } }}

AskTheRegistrar.java

If the class includes the word “CS483” (case sensitive) then the classmust have some spots open. Otherwise, the class is full.

Page 73: Java EE Programming

Java Application to Invoke the Functionality – LocalStudent.java

class LocalStudent{ public static void main( String args[] ) { System.out.println(); System.out.println( "LocalStudent running..." ); System.out.println( "--------------------------" ); System.out.println();

String studentClass; if ( args.length < 1 ) { studentClass = "CS483"; } else { studentClass = args[0]; } AskTheRegistrar currentRegistrationStatus = new AskTheRegistrar(studentClass); System.out.println( "The registration status for " +

studentClass + " is:"); System.out.println(" > “ + currentRegistrationStatus.getRegistrationStatus()); System.out.println(); System.out.println( "--------------------------" ); System.out.println( "LocalStudent finished." ); }}

In order to work, both classes just need to be in a directory within the current CLASSPATH environment variable

Page 74: Java EE Programming

74

Result when run...

By passing the argument “CS483”, the AskTheRegistrar service concludes that the student is registered

Page 75: Java EE Programming

75

Java RMI Example (with a server)

We now seek to move the AskTheRegistrar 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.

Currently, the AskTheRegistrar class has two member functions: the constructor and getRegistrationStatus.

The constructor will not be available remotely and so we need to create an alternative method to set the location.

These two functions, setClass and getRegistrationStatus, will be available to remote invocation and we can now create an interface detailing this decision.

Need to enhance the object AskTheRegistrar so that it can be remotely used

Page 76: Java EE Programming

76

RMI Server Example – Sequence Diagram

Page 77: Java EE Programming

77

AskTheRegistrarInterface.java

import java.rmi.*;

public interface AskTheRegistrarInterfaceextends Remote

{ public void setClass( String in_whichClass )

throws RemoteException; public String getRegistrationStatus( )

throws RemoteException;}

*Remember an interface is a contract that a class can choose to implement so there is no actual code in the interface itself

Page 78: Java EE Programming

78

New Version of AskTheRegistrar

See AskTheRegistrarRemote.java Imported java.rmi and java.rmi.server packages

to enable remote invocation capability Class inherits from the UnicaseRemoteObject

parent class This object means that a single instance (as opposed

to one instance per request) of the AskRemoteRegistrarRemote 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 theClass variable

Page 79: Java EE Programming

79

RMI Registry A client wishing to use a remote object will

need to know exactly where it is located RMI registry

Coordinated “phone book” that records every object’s name and address

Publishes object’s info in a well-known location rmiregistry.exe

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

Page 80: Java EE Programming

80

RMI Registry

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)

Page 81: Java EE Programming

81

RMI Server Example 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

Page 82: Java EE Programming

import java.rmi.*;import java.rmi.server.*;class AskTheRegistrarServer{ public static void main ( String[] args ) { try { Naming.rebind("//localhost/AskTheRegistrar", new AskTheRegistrarRemote());

System.out.println("AskTheRegistrar Server is ready."); System.out.println();

} catch (Exception e) { System.out.println("AskTheRegistrar Server unexpectedly quit. “ +"Exception message: " + e.getMessage()); } //end try } //end main} //end class

AskTheRegistrarServer.java

Page 83: Java EE Programming

83

RMI Server Example 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/AskTheRegistrar", new AskTheRegistrarRemote() );

. . .

Page 84: Java EE Programming

84

RMI Server Example 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.

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.

This directory name does not have to be the same as the actual remote object.

Page 85: Java EE Programming

85

RMI Server Example The second argument creates the actual remote

object that will accept requests from clients. 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 (LocationStudent) created its own instance of the AskTheRegistrar service class.

In the RMI version, we have a single instance of the AskTheRegistrar class that will be used by any and all clients.

Page 86: Java EE Programming

86

RMI Server Example 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:

Page 87: Java EE Programming

87

Client Example Create a client that accesses the

AskTheRegistrar remote object Two critical lines:

. . .AskTheRegistrarInterface theRegistrar =

(AskTheRegistrarInterface) Naming.lookup ( "//" + remoteServer + "/AskTheRegistrar" );

. . .System.out.println( " > " + theRegistrar.getRegistrationStatus());. . .

Page 88: Java EE Programming

88

Client Example 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 “AskTheRegistrar”. Note that what is returned is a reference to the interface we

initially created. 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

. . .AskTheRegistrarInterface theRegistrar =

(AskTheRegistrarInterface) Naming.lookup ( "//" + remoteServer + "/AskTheRegistrar" );

. . .System.out.println( " > " + theRegistrar.getRegistrationStatus());. . .

Page 89: Java EE Programming

89

Client Example We can now see the result of

running the client:

Page 90: Java EE Programming

90

Server Output This is the activity on the server:

Server displays the caller’s (client) IP address

Page 91: Java EE Programming

91

Java RMI Example (with a daemon)

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

Page 92: Java EE Programming

Java RMI with the Daemon Sequence Diagram

Page 93: Java EE Programming

93

Java RMI Example (with a daemon)

The remote object that we created in AskTheRegistrarRemote 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 AskTheRegistrarRemote to AskTheRegistrarActivation.

Page 94: Java EE Programming

import java.rmi.*;import java.rmi.server.*;import java.rmi.activation.*;public class AskTheRegistrarActivation

extends Activatable implements AskTheRegistrarInterface{ private String theClass; // + This constructor (which was not required when // we used the server-based form of RMI) will // be automatically called by the RMI daemon. // public AskTheRegistrarActivation(

ActivationID id, MarshalledObject data )

throws RemoteException { // + Register the object with the activation system // then export it on an anonymous port // super(id, 0); // + Here is our additional code. theClass = "(No class set)"; }

. . .}

AskTheRegistrarActivation.java

Page 95: Java EE Programming

95

Java RMI Example (with a daemon)

Instead of inheriting from UnicastRemoteObject, 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 & MarshalledObject

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.

Page 96: Java EE Programming

96

Java RMI Example (with a daemon)

Server Application See AskTheRegistrarRMIDSetup.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).

Page 97: Java EE Programming

97

To accomplish these alterations, we need a security manager to be available like so:

. . .

System.setSecurityManager( new RMISecurityManager());. . .

Java RMI Example (with a daemon)

Server Application

Page 98: Java EE Programming

98

Java RMI Example (with a daemon)

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

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 AskTheRegistrarActivation.policygrant

{ // + This allows the remote AskTheRegistrar object to accept // incoming connections from anywhere, as long as it is on // an unprivileged port (which is normally the case). // permission java.net.SocketPermission "*:1024-", "accept";};

Page 99: Java EE Programming

99

Java RMI Example (with a daemon)

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.

Page 100: Java EE Programming

100

Java RMI Example (with a daemon)

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:\CS483\AskTheRegistrarActivation.policy. Any other request for elevated permissions will be expressly denied.

grant { // + This allows the remote AskTheRegistrar object to // request the security policy in the file // Z:\CS483\AskTheRegistrar.policy. // + If this is not allowed, then the remote AskTheRegistrar // object will either not be allowed to registered, or // will be registered with no ability to make network // connections. // permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=Z:/CS483/AskTheRegistrarActivation.policy";};

Page 101: Java EE Programming

101

Run the daemon 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.

Start the daemon:C:> %JAVAHOME%\rmid –J-Djava.security.policy=RMID.policy

Page 102: Java EE Programming

102

Java RMI Example (with a daemon)

Next, we must register the AskTheRegistrar 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 AskTheRegistrar setup to connect to // the RMI registry. // permission java.net.SocketPermission "Alpha:1098", "connect";

// + This allows the AskTheRegistrar setup to connect to // the RMI daemon (background process). // permission java.net.SocketPermission "Alpha:1099", "connect";

};

Page 103: Java EE Programming

103

Java RMI Example (with a daemon)

Assuming that the remote AskTheRegistrar 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=AskTheRegistrarRMIDSetup.policyAskTheRegistrarRMIDSetup

Page 104: Java EE Programming

104

Java RMI Example (with a daemon)

It is worthwhile to note here that the remote object, AskTheRegistrarActivation, 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.

Page 105: Java EE Programming

105

Java RMI Example (with a daemon)

We need to make two more adjustments. 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 AskTheRegistrarActivation in our example), we employ the remote invocation compiler to whittle it down to just a stub.

C:> %JAVAHOME%\rmic AskTheRegistrarActivation

Page 106: Java EE Programming

106

Java RMI Example (with a daemon)

This will produce a file named AskTheRegistrarActivation_stub.class that needs to be distributed with the client application (in addition to the AskTheRegistrarInterface.class and LocalStudentClient.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.SocketPermission

"Alpha:1024-", "connect,resolve";};

Page 107: Java EE Programming

107

Java RMI Example (with a daemon)

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=LocalStudentClient.policyLocalStudentClient Alpha "CS483"

Page 108: Java EE Programming

108

Executed Client Applicationwith Reference to Policy File

Page 109: Java EE Programming

109

LocalStudent Client 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 CS483. 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).

Page 110: Java EE Programming

110

RMI Daemon 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.