Distributed Objects in Java - PowerPoint PPT Presentation

1 / 35
About This Presentation
Title:

Distributed Objects in Java

Description:

Provide a very brief overview of distributed computing using Java. ... catch (IOException e) { // handle exception: fail to create a socket ... catch (IOException e) ... – PowerPoint PPT presentation

Number of Views:30
Avg rating:3.0/5.0
Slides: 36
Provided by: hsiy
Category:

less

Transcript and Presenter's Notes

Title: Distributed Objects in Java


1
Distributed Objects in Java
  • Object-Oriented Software
  • Development Using Java
  • by Xiaoping Jia
  • (Chapter 12)

2
Objectives
  • Provide a very brief overview of distributed
    computing using Java.
  • Examine different technologies supporting
    distributed systems.

3
Outline
  • Socket-based Communication
  • Remote Method Invocation
  • Java Database Connectivity
  • Common Object Request Broker

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

5
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

6
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

7
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
8
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
9
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()
10
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)
11
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 gt 0) host
args0 else host
"localhost" Socket socket new
Socket(host, 8008)
12
A Simple Echo Client (cont)
BufferedReader in PrintWriter out
// send data to the server for
(int i 1 i lt 10 i)
System.out.println("Sending line " i)
out.println("line " i) out.flush()
out.println("BYE")
out.flush()
13
A Simple Echo Client (cont)
// receive data from the server
while (true) String str
in.readLine() if (str null)
break else
System.out.println(str)
catch (Exception e)
14
Outline
  • Socket-based Communication
  • Remote Method Invocation
  • Java Database Connectivity
  • Common Object Request Broker

15
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
16
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
17
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
18
Step 3
  • Create an instance of the server and register
    that server to an RMI registry.

Contract server new ServiceProvider() Naming.r
ebind(name, server)
19
Step 4
  • Generate stub and skeleton classes using RMI
    compiler.
  • Generates
  • ServiceProvider_Skel
  • ServiceProvider_Stub
  • Stub class also implements Contract.

20
Step 5
  • Develop a client that uses the service.
  • remoteObj is actually an instance of the stub
    class
  • name is of the form rmi//hostport/name

Remote remoteObj Naming.lookup(name) Contract
serverObj (Contract) remoteObj //
serverObj.aService() // remote method
invocation //
21
Class diagram
Proxy pattern
22
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)

23
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
24
RMI server example (contd)
// 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()

25
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)
26
Outline
  • Socket-based Communication
  • Remote Method Invocation
  • Java Database Connectivity
  • Common Object Request Broker

27
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

28
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
  • jdbcsubprotocolsubname (local)
  • jdbcsubprotocol//hostport/subname (remote)
  • subprotocol specifies driver connection
    mechanism
  • subname name of database
  • Returns Connection object

29
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

30
Outline
  • Socket-based Communication
  • Remote Method Invocation
  • Java Database Connectivity
  • Common Object Request Broker

31
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

32
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

33
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

34
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

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

36
Additional slides
37
Multi-Threaded Echo Server
  • To handle multiple requests simultaneously.
  • In the main() method, spawn a thread for each
    request.
  • public class MultiEchoServer
  • public static void main(String args)
  • try
  • ServerSocket s new ServerSocket(8009)
  • while (true)
  • Socket incoming s.accept()
  • new ClientHandler(incoming).start()
  • catch (Exception e)

38
Client Handler
public class ClientHandler extends Thread
protected Socket incoming public
ClientHandler(Socket incoming)
this.incoming incoming public void run()
try BufferedReader in
new BufferedReader( new
InputStreamReader(
incoming.getInputStream())) PrintWriter
out new PrintWriter( new
OutputStreamWriter(
incoming.getOutputStream()))
39
Client Handler (cont'd)
out.println("Hello! ...")
out.println("Enter BYE to exit.")
out.flush() while (true)
String str in.readLine() if (str
null) break else
out.println("Echo " str)
out.flush() if (str.trim().equals("BYE
")) break
incoming.close() catch (Exception e)

40
Visitor Counter
  • A server and an applet.
  • The server keeps the visitor count in a file, and
    sends the count to clients when requested.
  • No need for spawning thread, since only need to
    transmit an integer.
  • Read and write files.

41
Visitor Counter Server
public class CounterServer public static
void main(String args) System.out.println(
"CounterServer started.") int i 1
try // read count from the file
InputStream fin new
FileInputStream("Counter.dat")
DataInputStream din new
DataInputStream(fin) i din.readInt()
1 din.close() catch (IOException
e)
42
Visitor Counter Server (cont'd)
(class CountServer continued.) try
ServerSocket s new ServerSocket(8190)
while (true) Socket incoming
s.accept() DataOutputStream out
new DataOutputStream(
incoming.getOutputStream())
System.out.println("Count " i)
out.writeInt(i) incoming.close()
43
Visitor Counter Server (cont'd)
(class CountServer continued.)
OutputStream fout new
FileOutputStream("Counter.dat")
DataOutputStream dout new
DataOutputStream(fout)
dout.writeInt(i) dout.close()
out.close() i catch
(Exception e) System.out.println("CounterS
erver stopped.")
44
Counter Applet
public class Counter extends Applet
protected int count 0 protected Font font
new Font("Serif", Font.BOLD, 24)
public void init() URL url
getDocumentBase() try Socket t
new Socket(url.getHost(), 8190)
DataInputStream in new
DataInputStream(t.getInputStream()) count
in.readInt() catch (Exception e)

45
Counter Applet (cont'd)
(class CountServer continued.) public void
paint(Graphics g) int x 0, y
font.getSize() g.setColor(Color.green)
g.setFont(font) g.drawString("You are
visitor " count, x, y)

46
Broadcast Echo Server
  • To handle multiple requests simultaneously.
  • Broadcast messages received from any client to
    all active clients.
  • Need to keep track of all active clients.

47
Broadcast Echo Server (cont'd)
public class BroadcastEchoServer static
protected Set activeClients
new HashSet() public static void
main(String args) int i 1 try
ServerSocket s new ServerSocket(8010)
while (true) Socket incoming
s.accept() BroadcastClientHandler
newClient new BroadcastClientHandler(
incoming, i) activeClients.add(newClie
nt) newClient.start()
catch (Exception e)
48
Broadcast Client Handler
public class BroadcastClientHandler extends
Thread protected Socket incoming
protected int id protected BufferedReader in
protected PrintWriter out public
synchronized void sendMessage(String msg)
if (out ! null) out.println(msg)
out.flush()
49
Broadcast Client Handler (cont'd)
public BroadcastClientHandler(Socket incoming,
int id)
this.incoming incoming this.id id
try if (incoming ! null) in
new BufferedReader( new
InputStreamReader(
incoming.getInputStream()))
out new PrintWriter( new
OutputStreamWriter(
incoming.getOutputStream()))
catch (Exception e)
50
Broadcast Client Handler (cont'd)
public void run() if (in ! null
out ! null) sendMessage("Hello!
...") sendMessage("Enter BYE to exit.")
try while (true)
String str in.readLine() if (str
null) break else
// echo back to this client
sendMessage("Echo " str ) if
(str.trim().equals("BYE")) break
else
51
Broadcast Client Handler (cont'd)
// broadcast to other active
clients Iterator iter
BroadcastEchoServer.activeClients.iterator()
while (iter.hasNext())
BroadcastClientHandler t
(BroadcastClientHandler) iter.next()
if (t ! this)
t.sendMessage("Broadcast("
id ") " str)
incoming.close() //
this client is no longer active
BroadcastEchoServer.activeClients.remove(this)
catch (IOException e)
Write a Comment
User Comments (0)
About PowerShow.com