Advanced Java Programming Lecture 08 Trasmitting Java Objects over the Network dr inż. Wojciech...
-
Upload
hester-parker -
Category
Documents
-
view
213 -
download
0
Transcript of Advanced Java Programming Lecture 08 Trasmitting Java Objects over the Network dr inż. Wojciech...
AdvancedJava
Programming
Lecture 08Trasmitting Java Objects
over the Network
dr inż. Wojciech [email protected]://wbieniec.kis.p.lodz.pl
2
Sockets… allow low-level network communication.
A socket is one of the ends of two-way connection between the client and server.
Server is a program, which opens a sockets (well-known port) and waits until a client connects.
A client is connectig using any free temporary port (ephemeral port).
After the client and the servers get connected, the server proposes to move the „conversation” to another port.
3
Ports
Service name TCP port UDP port RFC document
echo 7 7 862
discard 9 9 863
daytime 13 13 867
chargen 19 19 864
time 37 37 868
The most common Internet services and corresponding port numbers
4
Opening a socketExample: Connect to the echo server and use this service to receive and send a text (until the server send the text "Bye"). To create a socket, you must initialize a class Socket from java.net package:
1. create a socket (create a connection)
s = new Socket("zly.kis.p.lodz.pl", 7);
2. read a text given from the user using a BufferedReader stream (here the text is read from the standard input – a keyboard)
BufferedReader kr = new BufferedReader(new InputStreamReader(System.in));
3. Build a stream that will send a text to the server and a stream reading from the server
PrintWriter pw=new PrintWriter(s.getOutputStream(),true); BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
5
Opening a socket
4. Implement communication procedures (receive the text until we send „bye”) while( !line.equals("bye") )
{
line=kr.readLine();
pw.println(line); line= br.readLine();
System.out.println("Line received: " + line); }
5. Close the streams.
br.close();
s.close();
6
Server sockets
1. Create an instance of the server socket try { fServerSocket = new ServerSocket(kPortNumber); System.out.println("TServer started..."); } catch (IOException e) { … }
2. Wait for the connection request from a client Socket theClientSocket; while (true) { if (fServerSocket == null) return; try { theClientSocket = fServerSocket.accept();
7
Server sockets
4. Break the connection theWriter.close() ; theClientSocket.close(); } catch (IOException e) { System.err.println("Ugly exception: " + e.getMessage ()); System.exit(1); } }
3. Accept the client request and send the message to the client PrintWriter theWriter = new PrintWriter( new OutputStreamWriter(theClientSocket.getOutputStream())) ; theWriter.println(new java.util.Date().toString()) ; theWriter.flush();
Datagram socket
Provides a mechanism for sending and receiving datagrams.The most common case are UDP packets.
DatagramSocket(SocketAddress bindaddr)Create a socked and bind it to a given socket address
Construction:DatagramSocket()Create a socket creation and bind it a free port on the local machine.
DatagramSocket(int port)Create a socket creation and bind it a specific port on the local machine.
DatagramSocket(int port, InetAddress laddr)Create a socket creation and bind it a specific port to the given machine.
We do not distinguish here a Server and a Client, the link is not established. Packets are simply sent out to the world and there is no guarantee that they arrive and will be prosecced in a correct order
Datagram socket
void bind(SocketAddress addr)bind the socket to a given address
DatagramSocket class has two communication methodssend(DatagramPacket data)
Enables to send a single packet. recive(DatagramPacket data).
holds the current thread until receive a message.
Methods for handling the sockets:
void close()close the socket
void connect(InetAddress address, int port), void connect(SocketAddress addr)
bind the socket with a given remote address and the port (the communication is limited only to this address).
void disconnect()disconnecting a socket.
Datagram packet
A datagram packet (usually UDP) is represented by DatagramPacket class.It provides both input and output buffers.It enables configuration of some UDP packet parameters and add data field.
Most important UDP packed fields in DatagramPacket class are:
buf – a byte array for transmitted data,length – count of data bytes;offset – data shift from the beginning of the array;address – an address of the source or destination socket
Datagram packet
DatagramPacket(byte[] buf, int length)
DatagramPacket(byte[] buf, int length, InetAddress address, int port)
DatagramPacket(byte[] buf, int offset, int length)
DatagramPacket(byte[] buf, int offset, int length, InetAddress address, int port)
DatagramPacket(byte[] buf, int offset, int length, SocketAddress address)
DatagramPacket(byte[] buf, int length, SocketAddress address)
Initialization of the DatagramPacket object
where:buf – a byte array for transmitted data,length – count of data bytes;offset – data shift from the beginning of the array;address – an address of the source or destination socket
Multicast socketThe MulticastSocket class is deigned to send and receive multicast datagram packets.
D class is a range <224.0.0.0; 239.255.255.255 >244.0.0.0 is reserved and should not be used in a standard communication
The multicast connection cannot be routed, it resembles UDP.
In multicast packets single IP address (source or destination) is replaced by multicast group address, which a host can join.
Group addresses have a D class IP number and a standard port number
Multicast sockets behave as usual sockets, but they have some additional methods joinGroup(InetAddress adr) leaveGroup(InetAddress adr)
The methods are used to join or leave a multicast group.After joining a group, each member can send and receive packets.
Multicast example
String msg = "Hello";
InetAddress group = InetAddress.getByName("228.5.6.7");
MulticastSocket s = new MulticastSocket(6789);
s.joinGroup(group);
DatagramPacket hi =
new DatagramPacket(msg.getBytes(),
msg.length(), group, 6789);
s.send(hi); // get their responses!
byte[] buf = new byte[1000];
DatagramPacket recv = new DatagramPacket(buf, buf.length);
s.receive(recv);
// OK, I'm done talking - leave the group...
s.leaveGroup(group);
14
Java RMIRemote Method Invocation – Remote procedure call
Objective RPC for Java
The mechanism is simple
Th brand product
RMI system allows an object running in one Java virtual machine to invoke methods on an object running in another Java virtual machine.
Compared to object serialization through the socket it provides higher level of abstraction
In fact – it is implemented on sockets and serialization
15
The Idea of RPC (remote procedure call)
Local procedure call
Remote procedure call paradigm: Birel and Nelson (1984)
The client-server model allows manage a wide range of problems, but it has some limits:• he reference to input and output (receive / send)• there is a problem of data representation (heterogeneous systems)• the model is data oriented
16
The Idea of RPC
Server stub – represents a client at the server side. The procedure call is replaced by the client stub call.
Possible problems:Calling and called procedures run on different machines in different address spaces
Problem in pointer usage.
The machines can have diferent systems of data representation.
There is a problem of emergency situations handling
The connectors between server and client are:Client stub – represents a server at the client side
17
How does remote procedure work
1. The application calls the client stub
2. The stub creates a message and passes it to the OS kernel
3. The kernel sends the message to the remote machine
4. The server stub deserializes the parameters and calls the server
5. Server runs the procedure and returns the result to the server stub
6. The stub packs the result and sends it back in the same way
7. The client stub receives the message and deserializes the result as Java Object
18
The properties of RPC
• No multithreading support• Weak possibilities of the client authorization• Possibility of program number conflict• Function header may have only one argument• Difficult use of pointers in function arguments• C support only
advantages:• Simplicity• Good efficiency• Commonness of the standard
drawbacks:
19
Objective processing model
Properties of the objective processing model
• Encapsulation• Inheritance• Polymorfism
• Module programming• Reusable code• Development simplification
20
Objective processing modelMotivation:
– CORBA (Common Object Request Broker Architecture) – OMG– DCOM (Distributed Component Object Model) – Microsoft– SOAP (Simple Object Access Protocol ) – Microsoft– .NET Remoting – Microsoft– Ninf, NetSolve/GridSolve (grids)– Java RMI (Remote Method Invocation) – Sun Microsystems– Globe – Vrije Uniwersyty
Provide the client with object-oriented RPC mechanism.
Objective RPC + services = a platform for distributted processing
The client sees only an interface of the object, without its implementation
The examples:
21
RMI developmentDefine a remote
interface
Implementthe interface
javac
rmicClientimplementation
javac
Run the client
Client stub(.class)
Server class(.class)Server skel
(.class)
Run RMI registry
Run server objects
Register remote objects
1
(.java)
(.class)
2
3
4
5
6
7
8
9
10(.class)
(.java)
uses
C L I E N T S E R V E R
RMI Example: Create an Interface
Interface declares the methods (and arguments to them) which will be available in a class which
implements it.
public interface myRMIInterface extends java.rmi.Remote{ public java.util.Date getDate() throws java.rmi.RemoteException;}
Create class which implements interfejs myRMIInterface
Class must implement the interface which has been created in last step.
import java.rmi.*;import java.rmi.server.UnicastRemoteObject;
public class myRMIImpl extends UnicastRemoteObject implements myRMIInterface{ public java.util.Date getDate() { return new java.util.Date(); } // …
A Remote Object
● A remote object is an instance of a class that implements a remote interface.
● This class has to extend java.rmi.UnicastRemoteObject.
● It includes a constructor which exports the object to the RMI system when it is created, making it the object visible to the outside world.
Create class which implements interfejs myRMIInterface (part 2)
//. . . public myRMIImpl(String name) throws RemoteException { super(); try { Naming.rebind(name, this); } catch(Exception e) { System.out.println("Exception occurred: " + e); } }}
Create server
In this example server has two roles:● Installs new RMISecurityManager● Creates an instance of the myRMIImpl class, (with
name "myRMIImplInstance"). ● myRMIImpl object register object with the RMI
registry. ● After running code, object will be available as
remote clients as "rmi://"
Create server (part 2)import java.rmi.*;import java.rmi.server.UnicastRemoteObject;
public class myRMIServer{ public static void main(String[] argv) { System.setSecurityManager(new RMISecurityManager()); try { myRMIImpl implementation = new myRMIImpl("myRMIImplInstance"); } catch (Exception e) { System.out.println("Exception occurred: " + e); } }}
Create the client
Client will connect to the server by using
naming.lookup()
On the begining, the Client installs a new RMI Security Manager, then uses the static method
naming.lookup()
to get a reference to the remote object.
Create a clientimport java.rmi.*;import java.rmi.registry.*;import java.rmi.server.*;import java.util.Date;public class myRMIClient{ public static void main(String[] argv){ System.setSecurityManager(new RMISecurityManager()); try{ myRMIInterface myServerObject = (myRMIInterface) Naming.lookup("rmi://"+argv[0]+"/myRMIImplInstance");//invoke method on server object Date d = myServerObject.getDate(); System.out.println("Date on server is " + d); } catch(Exception e){ System.out.println("Exception occured: " + e); System.exit(0); } System.out.println("RMI connection successful"); } }
30
RMI and memory management
Main problem: distributed garbage collection
For each remote object there is a counter of its remote references.
RMI protocol provides its update.
Remote objects may be destroyed only after all local and remote references disappear.
31
RMI and memory management
class Server … implements Unreferenced
…
void unreferened()
{
}
For example: we would like to close the server when it is no longer needed - the last remote object disappeares.
Solution: the server should implement Unreferenced interface.
The method unreferenced() is invoked when a list of references is empty.
32
Advanced RMI capabilitiesTunelling over HTTPRMI is able to provide connectivity even in the case of blocking such direct communication through the firewall. In this case, you can use the HTTP protocol.
Running the services on demandjava.rmi.server.UnicastRemoteObject is not the only server class.We can use java.rmi.activation.Activatable instead.This class, along with a set of auxiliary classes, provide a fairly complicated way to run services on demand.In particular, this means that remote references may be valid after the destruction of the object to which they pointed, even after restarting the virtual machine on which the object is located. It is not possible for UnicastRemoteObject.
Stub downloadRMI may automatically download servers stubs, which wants to use it.Although, it requires a bit more labour (you need to create a security manager)
Use of CORBARMI uses its own protocol JRMP (Java Remote Method Protocol).But CORBA is also available - RMI over IIOP (Internet Inter-ORB Protocol). You may write an RMI interface, generate skeletons and stubs using CORBA and an IDL file.
33
Summary
RMI is slower than RPC and even CORBA
Java integratedTo remotely invoke a method it does not need to convert the interfaces to IDL. In DCOM or CORBA this conversion is necessary.
Allows rapid and easy distributed application development
Built-in multithreading allows running other program functions
Parameters transmitted when calling methods between virtual machines can be ordinary Java objects - Impossible in DCOM and CORBA.
Java-RMI supports the Distributed Garbage Collection, which works as local Garbage Collectors in each of the virtual machines
Due to the strongly association with Java RMI is able to interact with inherited classes. This is not possible in DCOM or CORBA, because those approaches are typically static.
Serialization of Java Objects
RMI employs the mechanism of object serialization.Each object to be sent via RMI must implement the interface java.io.Serializable
As well as in explicit object serialization, in case we need and a custom serialization we have to oveeride additional methods for the object:
private void writeObject(java.io.ObjectOutputStream out) throws IOException;
private void readObject(java.io.ObjectInputStream in)throws IOException, ClassNotFoundException;
Remote methods may use objects as parameters and return value.
public MyObject2 myMethod(MyObject1 theObject)
Registration of serversObject factories
rmiregistry – starts the registry for remote services
The connection string for the service:[rmi:]//<DNS name or IP>[:<port>]/<service name>
Methos used for serivce registration
public static void bind(String name, Remote obj)public static void unbind(String name)public static void rebind(String name, Remote obj)public static String[] list(String name)public static Remote lookup(String name)
The mechanism of the factory: we register one master object, which has methods for creating slave objects on demand – those are particular remote services. The methods return the references to these objects.
36
Another example – using factory„Factory” will be the master remote object.This object will start and manage the slave objects „Server” and „Client”
37
Implementation – the factory
38
Implementation – the server
39
Implementation – the client
40
Implemetation – the client
41
Running the applicationCompilation
javac *.javarmic theFactory theClient theServer
Running the server
rmiregistryjava theFactory
Running the client:
java theClient