350 likes | 570 Views
Distributed Objects in Java. Object-Oriented Software Development Using Java by Xiaoping Jia (Chapter 12). Objectives. Provide a very brief overview of distributed computing using Java. Examine different technologies supporting distributed systems. Outline. Socket-based Communication
E N D
Distributed Objects in Java Object-Oriented Software Development Using Java by Xiaoping Jia (Chapter 12)
Objectives • Provide a very brief overview of distributed computing using Java. • Examine different technologies supporting distributed systems.
Outline • Socket-based Communication • Remote Method Invocation • Java Database Connectivity • Common Object Request Broker
Distributed systems • Distributed systems consists of components that reside and execute on different hosts. • They do not physically share any storage space. • Communication exchange take place over network connections. • The environment can be heterogenous (different programming languages, operating systems, processor types).
Socket-based communication • Sockets – the endpoints of two-way communications between two distributed components • Source and destination address • Source and destination port • Address – a unique identifier for a machine on a network • IP address • Hostname • Port – a numeric identifier for a particular connection on a given machine
Sockets in Java • Server socket class: ServerSocket • Wait for requests from clients. • After a request is received, a client socket is generated. • Client socket class: Socket • An endpoint for communication between two apps/applets. • Obtained by • Contacting a server • Generated by the server socket • Communication is handled by input/output streams. • Socket provides an input and an output stream. • Uses java.net.* package
Server socket example try { ServerSocket s = new ServerSocket(8008); while (true) { Socket incoming = s.accept(); // Handle a client } } catch (IOException e) { // handle exception: fail to create a socket }
Client socket example try { Socket s = new Socket(host,8008); PrintWriter out = new PrintWriter( new OutputStreamWriter(s.getOutputStream())); BufferedReader in = new BufferedReader( new InputStreamReader(s.getInputStream())); // send and receive data … in.close(); out.close(); s.close(); } catch (IOException e) { // handle exception: connect failed }
A Simple Echo Server import java.io.*; import java.net.*; public class EchoServer { public static void main(String[] args) { try { ServerSocket s = new ServerSocket(8008); while (true) { Socket incoming = s.accept(); BufferedReader in … PrintWriter out … out.println("Hello! ...."); out.println("Enter BYE to exit."); out.flush();
A Simple Echo Server (cont'd) while (true) { String str = in.readLine(); if (str == null) { break; // client closed connection } else { out.println("Echo: " + str); out.flush(); if (str.trim().equals("BYE")) break; } } incoming.close(); } } catch (Exception e) {} } }
A Simple Echo Client import java.io.*; import java.net.*; public class EchoClient { public static void main(String[] args) { try { String host; if (args.length > 0) { host = args[0]; } else { host = "localhost"; } Socket socket = new Socket(host, 8008);
A Simple Echo Client (con’t) BufferedReader in … PrintWriter out … // send data to the server for (int i = 1; i <= 10; i++) { System.out.println("Sending: line " + i); out.println("line " + i); out.flush(); } out.println("BYE"); out.flush();
A Simple Echo Client (con’t) // receive data from the server while (true) { String str = in.readLine(); if (str == null) { break; } else { System.out.println(str); } } } catch (Exception e) {} } }
Outline • Socket-based Communication • Remote Method Invocation • Java Database Connectivity • Common Object Request Broker
Remote Method Invocation (RMI) • RMI simplifies the programming model of distributed applications – no explicit connections • Uses java.rmi.* package. Client Server Client wants to call server.m(); actual call is stub.m() Server executes m() and returns to Skeleton Skeleton calls server.m() Stub returns result to Client 1 6 3 4 Stub serializes the args and sends request to Skeleton Stub Skeleton 2 JVM JVM 5 Skeleton sends results back to Stub
Using RMI • Define an interface for the remote object, which becomes the contract interface between server and clients. public interface Contract extends remote { public void aService(…) throws RemoteException; // other services … }
Step 2 • Define a service implementation class that implements the Contract interface. • The implementation class must extend UnicastRemoteObject. public class ServiceProvider extends UnicastRemoteObject, implements Contract { public void aService(…) throws RemoteException { … } // other services }
Step 3 • Create an instance of the server and register that server to an RMI registry. Contract server = new ServiceProvider(…); Naming.rebind(name, server);
Step 4 • Generate stub and skeleton classes using RMI compiler. • Generates: • ServiceProvider_Skel • ServiceProvider_Stub • Stub class also implements Contract.
Step 5 • Develop a client that uses the service. • remoteObj is actually an instance of the stub class • name is of the form rmi://host:port/name Remote remoteObj = Naming.lookup(name); Contract serverObj = (Contract) remoteObj; // … serverObj.aService(…); // remote method invocation // …
Class diagram Proxy pattern
Subject Request() Proxy Request() RealSubject Request() realSubject Proxy pattern • Interface inheritance is used to specify the interface shared by Proxy and RealSubject. • Delegation is used to catch and forward any accesses to the RealSubject (if desired)
RMI server example // Contract interface public interface Hello extends java.rmi.Remote { String sayHello() throws RemoteException; } // Server implementation import java.rmi.*; import java.rmi.server.UnicastRemoteObject; public class HelloImpl extends UnicastRemoteObject implements Hello { private String name; public HelloImpl(String s) throws RemoteException { super(); name = s; } public String sayHello() throws RemoteException { return “Hello world”; }
RMI server example (cont’d) // main creates an instance of HelloImpl and binds it to // a name “HelloServer” in the RMI registry public static void main(String args[]) { System.setSecurityManager(new RMISecurityManager()); try { HelloImpl obj = new HelloImpl(“HelloServer”); Naming.rebind(“HelloServer”, obj); } catch (Exception e) { e.printStackTrace(); } } }
RMI client example import java.awt.*; import java.rmi.*; public class HelloApplet extends Applet { String message=“”; public void init() { try { Hello obj = (Hello) Naming.lookup(“rmi://localhost/HelloServer”); message = obj.sayHello(); } catch (Exception e) { e.printStackTrace(); } } public void paint(Graphics g) { g.drawString(message, 25, 50); } }
Outline • Socket-based Communication • Remote Method Invocation • Java Database Connectivity • Common Object Request Broker
Java Database Connectivity (JDBC) • JDBC allows Java applications to interface with databases. • Uses java.sql.* package • Four types: • JDBC-ODBC bridge • Provides JDBC access via existing ODBC drivers • Native-API • Converts JDBC calls to DBMS calls • JDBC-Net protocol • Translates JDBC calls into DBMS independent protocol • Native protocol • Converts JDBC calls to the protocol used by DBMS directly
Establishing a connection with JDBC • Load the JDBC class driver Class.forName(JDBCDrivername); Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); • Connect to database DriverManager.getConnection(url, “ID”, “password”); • url: • “jdbc:subprotocol:subname” (local) • “jdbc:subprotocol://host[:port]/subname” (remote) • subprotocol – specifies driver connection mechanism • subname – name of database • Returns Connection object
Some methods • Connection class: • createStatement() – new Statement object • commit() – commits database changes • close() – releases the database and all resources associated with this Connection • Statement class: • executeQuery(sqlstring) – returns resultSet object • executeUpdate(sqlstring) – INSERT, UPDATE, DELETE SQL statements • close() – releases all resources associated with this Statement
Outline • Socket-based Communication • Remote Method Invocation • Java Database Connectivity • Common Object Request Broker
Client Server 1 6 3 4 Stub Skeleton 2 ORB ORB 5 Common Object Request Broker Architecture (CORBA) • CORBA is an open, distributed object-computing infrastructure • Enables Java applications to talk to components written in other languages
Interface Definition Language • IDL is a programming-language-independent language for specifying the contract interface of a CORBA server • IDL compiler • Translates interfaces written in IDL to various programming languages • Generates stubs and skeletons
Object Request Broker • ORB defines the mechanism and interfaces that enable objects to make requests and receive responses in a distributed environment • Infrastructure for platform-independent communication
Using CORBA • Client requests service • ORB locates a server that can accept the service • ORB sends arguments, invokes the method on the server returns results to client • Client interacts with stub and does not need to know where the actual server object is located
Summary • Presented an overview of distributed computing using Java. • Java programs communicate with other machines through sockets or RMI. • JDBC drivers enable Java programs to communicate with databases. • CORBA enables Java programs to communicate with other components written in other languages.