Advanced Java Programming Lecture 08 Trasmitting Java Objects over the Network dr inż. Wojciech Bieniecki wbieniec@kis.p.lodz.pl http://wbieniec.kis.p.lodz.pl 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. 2 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 3 Opening a socket Example: 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())); 4 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(); 5 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(); 6 Server sockets 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(); 4. Break the connection theWriter.close() ; theClientSocket.close(); } catch (IOException e) { System.err.println("Ugly exception: " + e.getMessage ()); System.exit(1); } } 7 Datagram socket Provides a mechanism for sending and receiving datagrams. The most common case are UDP packets. 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 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. DatagramSocket(SocketAddress bindaddr) Create a socked and bind it to a given socket address Datagram socket Methods for handling the sockets: void bind(SocketAddress addr) bind the socket to a given address 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. DatagramSocket class has two communication methods send(DatagramPacket data) Enables to send a single packet. recive(DatagramPacket data). holds the current thread until receive a message. 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 Initialization of the DatagramPacket object 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) 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 socket The MulticastSocket class is deigned to send and receive multicast datagram packets. 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 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 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); Java RMI Remote Method Invocation – Remote procedure call 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 Objective RPC for Java The mechanism is simple Th brand product 14 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) 15 • the model is data oriented The Idea of RPC 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 Server stub – represents a client at the server side. The procedure call is replaced by the client stub call. 16 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 17 The properties of RPC advantages: • • • Simplicity Good efficiency Commonness of the standard drawbacks: • • • • • • 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 18 Objective processing model Properties of the objective processing model •Encapsulation •Module programming •Inheritance •Reusable code •Polymorfism •Development simplification 19 Objective processing model Motivation: 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: – 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 20 RMI development 1 Define a remote interface 2 Implement the interface (.java) 3 8 Client implementation (.java) 9 javac uses javac 4 Client stub (.class) (.class) rmic Server skel (.class) Server class (.class) (.class) 10 5 Run the client 6 7 Run RMI registry Run server objects Register remote objects 21 CLIENT SERVER 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 client import 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"); } } 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. 30 RMI and memory management 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. class Server … implements Unreferenced … void unreferened() { } 31 Advanced RMI capabilities Tunelling over HTTP RMI 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. Stub download RMI may automatically download servers stubs, which wants to use it. Although, it requires a bit more labour (you need to create a security manager) Running the services on demand java.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. Use of CORBA RMI 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. 32 Summary RMI is slower than RPC and even CORBA Java integrated To remotely invoke a method it does not need to convert the interfaces to IDL. In DCOM or CORBA this conversion is necessary. 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. 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 Allows rapid and easy distributed application development Built-in multithreading allows running other program functions 33 Serialization of Java Objects Remote methods may use objects as parameters and return value. public MyObject2 myMethod(MyObject1 theObject) 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; Registration of servers Object 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 public public public public static static static static static void bind(String name, Remote obj) void unbind(String name) void rebind(String name, Remote obj) String[] list(String name) 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. Another example – using factory „Factory” will be the master remote object. This object will start and manage the slave objects „Server” and „Client” 36 Implementation – the factory 37 Implementation – the server 38 Implementation – the client 39 Implemetation – the client 40 Running the application Compilation javac *.java rmic theFactory theClient theServer Running the server rmiregistry java theFactory Running the client: java theClient 41