Introduction to Java IV - PowerPoint PPT Presentation

1 / 127
About This Presentation
Title:

Introduction to Java IV

Description:

Patrick Naughton and Herbert Schildt, The Complete Reference Java 2, 3rd ed. ... Merlin Hughes, Michael Shoffner, Derek Hamner, with Umesh Bellur, JAVA Network ... – PowerPoint PPT presentation

Number of Views:651
Avg rating:3.0/5.0
Slides: 128
Provided by: shyhka
Category:

less

Transcript and Presenter's Notes

Title: Introduction to Java IV


1
Introduction to Java (IV)
  • Shyh-Kang Jeng
  • Department of Electrical Engineering/
  • Graduate Institute of Communication Engineering
  • National Taiwan University

2
References
  • Patrick Naughton and Herbert Schildt, The
    Complete Reference Java 2, 3rd ed., McGraw-Hill,
    1999.
  • Merlin Hughes, Michael Shoffner, Derek Hamner,
    with Umesh Bellur, JAVA Network Programming, 2nd
    ed., Manning, 1999.

3
Streams
  • A stream represents an endpoint of a one-way
    communication channel
  • The connection can take the form of a link
    through a network, a memory buffer, a file
  • Streams provide a uniform data interface for
    applications

4
Class OutputStream
  • Provides the superclass for all concrete output
    stream implementation (to a file or to a network
    or to a memory buffer)
  • Methods defined
  • abstract void write(int b)
  • void write(byte b, int off, int len)
  • void write(byte b)
  • void flush()
  • void close()

5
Class InputStream
  • Is the superclass for all input stream
  • Some methods
  • abstract int read()
  • int read(byte b, int off,
  • int len)
  • int read(byte b)
  • int available()
  • void close()
  • long skip(long n)

6
Class File (1)
  • Represents a system-independent file name
  • Provides methods to determine information about
    the actual file of the specified name as well as
    methods to modify the files attributes

7
Class File (2)
  • Constructors
  • File(String path)
  • File(String path, String name)
  • File(File dir, String name)
  • Some methods
  • boolean exists()
  • long length()
  • String getName()
  • String getPath()
  • String list()
  • boolean delete()

8
Class FileOutputStream (1)
  • Allows sequential data to be written to a file

9
Class FileOutputStream (2)
  • Constructors
  • FileOutputStream(String name)
  • FileOutputStream(File file)
  • FileOutputStream(String name, boolean append)

10
Class FileInputStream (1)
  • Allows one to read sequential data from a file

Readme.txt
FileInputStream
11
Class FileInputStream (2)
  • Constructors
  • FileInputStream(String name)
  • FileInputStream(File file)

12
Class Writer
  • Is the superclass of all character output stream
  • Methods defined
  • void write(int c)
  • void write(char cbuf)
  • abstract void write(char cbuf, int off, int
    len)
  • void write(String str)
  • void write(String str, int off, int len)
  • abstract void flush()
  • abstract void close()

13
Class Reader
  • Is the superclass of all character input streams
  • Some methods
  • int read()
  • int read(char cbuf)
  • abstract int read(char cbuf, int off, int len)
  • long skip(long n)
  • boolean ready()
  • abstract void close()
  • void reset()

14
Class OutputStreamWriter (1)
  • Provides a character-oriented Writer bridge to a
    byte-oriented OutputStream channel

15
Class OutputStreamWriter (2)
  • Constructors
  • OutputStreamWriter(
  • OutputStream out )
  • OutputStreamWriter(
  • OutputStream out, String enc )

16
Class InputStreamReader (1)
  • Represents a character-oriented bridge out of a
    byte-oriented InputStream

17
Class InputStreamReader (2)
  • Constructors
  • InputStreamReader(
  • InputStream in)
  • InputStreamReader(
  • InputStream in, String enc)

18
Class BufferedWriter (1)
  • Provides write-buffering on the attached stream
  • All data written to this class are stored in an
    internal buffer until either the buffer becomes
    full, flush() is called, or close() is called

flush()
Writer
BufferedWriter
19
Class BufferedWriter (2)
  • Constructors
  • BufferedWriter( Writer out )
  • BufferedWriter( Writer out,
  • int sz )

20
Class BufferedReader (1)
  • Provides buffering on the attached stream
  • Data are read in large chunks from the attached
    stream into an internal buffer and can then be
    efficiently read in small volumes from the buffer

21
Class BufferedReader (2)
  • Constructors
  • BufferedReader( Reader in )
  • BufferedReader( Reader in,
  • int sz )

22
Object Streams
  • Object streams allow complete objects to be
    written to and read from a communication channel
    without much effort on the part of the programmer
  • Object streams are attached to an underlying
    communications channel, such as a file or a
    socket
  • The process to write/read the object status
    to/from byte streams is called serialization/deser
    ialization

23
Interface ObjectOutput
  • Some methods
  • void close()
  • void flush()
  • void writeObject(Object obj)

24
Class ObjectOutputStream (1)
  • Implements the ObjectOutput interface
  • Attaches to an existing OutputStream

25
Class ObjectOutputStream (2)
  • Constructor
  • ObjectOutputStream(
  • OutputStream outs)
  • Some methods
  • void writeChars(String str)
  • void writeInt(int I)
  • void writeDouble(double d)
  • final void writeObject(
  • Object obj)

26
Interface ObjectInput
  • Some methods
  • int available
  • void close()
  • Object readObject()
  • long skip(long numBytes)

27
Class ObjectInputStream (1)
  • Implements the ObjectInput interface
  • Attaches to an existing InputStream

readObject
28
Class ObjectInputStream (2)
  • Constructor
  • ObjectInputStream(
  • InputStream inStream)
  • Some methods
  • char readChar()
  • double readDouble()
  • int readInt()
  • final Object readObject()

29
Interface Serializable
  • A marker interface used by classes to indicate
    that they may be serialized by the default
    serialization mechanism
  • Defines no methods or data

30
SerializationDemo (1)
  • import java.io.
  • public class MyClass implements Serializable
  • String s
  • int i
  • double d
  • public MyClass( String s, int i, double d )
  • this.s s
  • this.i i
  • this.d d

31
SerializationDemo (2)
  • public String toString()
  • return "s " s " i " i " d "
    d

32
SerializationDemo (3)
  • public class MySubclass extends MyClass
  • int k
  • public MySubclass(
  • String s, int i, double d,
  • int k)
  • super( s, i, d )
  • this.k k
  • public String toString()
  • return super.toString()
  • " k " k

33
SerializationDemo (4)
  • public class SerializationDemo
  • public static void main(
  • String args )
  • try
  • MyClass object1 new
  • MyClass( "Hello", -7,
  • 2.7e10)
  • System.out.println("object1"
  • object1)
  • FileOutputStream fos new
  • FileOutputStream("serial")

34
SerializationDemo (5)
  • ObjectOutputStream oos new
  • ObjectOutputStream(fos)
  • oos.writeObject(object1)
  • MySubclass subObject new
  • MySubclass("Hi", 5, 0.3,4)
  • object1 subObject
    System.out.println(
  • "object1" object1 )
  • oos.writeObject(object1)
  • oos.flush()
  • oos.close()

35
SerializationDemo (6)
  • catch(Exception e)
  • System.out.println(
  • "Exception during serialization
  • e)
  • System.exit(0)
  • try
  • MyClass object2
  • FileInputStream fis new
  • FileInputStream( "serial" )
  • ObjectInputStream ois new
  • ObjectInputStream( fis )

36
SerializationDemo (7)
  • object2 (MyClass)
  • ois.readObject()
  • System.out.println(
  • "object2 " object2 )
  • object2 (MyClass)
  • ois.readObject()
  • System.out.println(
  • "object2 " object2 )
  • ois.close()

37
SerializationDemo (8)
  • catch( Exception e )
  • System.out.println(
  • "Exception during deserialization "
  • e )
  • System.exit(0)

38
Package java.net
  • Together, java.io and java.net packages contain
    all the tools needed for building complex
    networked applications
  • Encapsulate the socket paradigm

39
Client/Server and Sockets
  • A server is anything that has some resource that
    can be shared
  • A client is an entity that wants to gain access
    to a particular server
  • Clients and servers communicate with sockets

client
server
40
Connection Ports
  • A port is a numbered socket on a particular
    machine
  • A server can serve many different clients at
    once, as well as serving many different types of
    information, through many ports
  • A server process is said to listen to a port
    until a client connects to it
  • A server is allowed to accept multiple clients
    connected to the same port number, although each
    session is unique

41
Reserved Ports
  • Port number is from 1 to 65535
  • TCP/IP reserves the lower 1024 ports for
    specified protocols
  • Some reserved ports
  • FTP 21
  • Telnet 23
  • Email 25
  • Finger 79
  • HTTP 80
  • Netnews 119

42
Internet Addressing
  • An IP address is a 32-bit integer, referred to as
    a sequence of four numbers between 0 and 255
    separated by dots
  • Examples of IP classes and subnets
  • Class A 126. xx. xx. xx
  • Class B 191. 12. xx. xx
  • Class C 223. 12. 34. xx
  • Loopback address (localhost)
  • 127. 0. 0. 1
  • Domain Name
  • Example www.ntu.edu.tw

43
Class InetAddress
  • Provides abstracted access to IP addresses
  • Easily portable to IPv6 (128-bit address)
  • No constructors
  • Instantiated by using static methods
  • InetAddress getByName(
  • String host)
  • InetAddress getLocalHost()
  • Some methods
  • byte getAddress()
  • String getHostName()

44
Class URL
  • Example of Uniform Resource Locator (URL)
  • http//www.ntu.edu.tw80/index.html
  • Some Constructors
  • URL(String urlSpecifier)
  • URL(String protocolName,
  • String hostName, int port, String path)
  • Some method
  • InputStream openStream()

URL
InputStream
45
GrabbingWebPage (1)
  • import java.io.
  • import java.net.
  • public class GrabbingWebPage
  • public static void main(
  • String args)
  • try
  • URL url new URL(
  • "http//www.ntu.edu.tw/index.html")
  • InputStream in
  • url.openStream()
  • Reader reader new
  • InputStreamReader(in)

46
GrabbingWebPage (2)
  • BufferedReader bufferedReader
  • new BufferedReader( reader )
  • PrintWriter console new PrintWriter(
    System.out )
  • String line
  • while((line
  • bufferedReader.readLine()) ! null)
  • console.println( line )
  • console.flush()
  • bufferedReader.close()
  • catch ( Exception e )
  • System.out.println( e )

47
Class Socket (1)
  • Using this class, a client can establish a
    stream-based communication channel with a remote
    host port which the server is listening to
  • Constructors
  • Socket(String host, int port)
  • Socket(InetAddress address,
  • int port)

Socket
InputStream
OutputStream
hostport
48
Class Socket (2)
  • Some methods
  • InputStream getInputStream()
  • OutputStream getOutputStream()
  • void close()
  • InetAddress getInetAddress()
  • int getPort()

49
Hypertext Transfer Protocol (HTTP)
  • Defines the precise manner in which Web clients
    communicate with Web servers
  • HTTP/1.0 is the most popular version today
  • Stages of a simple web transition

Opens connection
Sends request
client
server
Responds
Close connection
50
HTTP 1.0
  • Status code category
  • 2xx (successful)
  • 4xx (client error)
  • 5xx (server error)
  • A GET request
  • GET index.htm HTTP/1.0
  • HTTP header
  • HTTP/1.0 200 OK
  • Date Fri, 23 Mar 2001 152000 GMT
  • Content-Length 359
  • Content-Type text/html

51
HTTPClientDemo (1)
  • import java.net.
  • import java.io.
  • public class HTTPClientDemo
  • public static void main(
  • String args)
  • try
  • InetAddress address
  • InetAddress.getLocalHost()
  • Socket s new Socket(
  • address, 8080 )
  • Client client new
  • Client( s )

52
HTTPClientDemo (2)
  • client.getFile( "index.htm" )
  • s.close()
  • catch (Exception e)
  • System.out.println(
  • "Client error " e )

53
HTTPClientDemo (3)
  • class Client
  • Socket s
  • public Client( Socket s )
  • this.s s
  • public void getFile( String file ) throws
    IOException
  • int c
  • OutputStream out
  • s.getOutputStream()

54
HTTPClientDemo (4)
  • InputStream in
  • s.getInputStream()
  • String str "GET " file
  • " HTTP\1.0 \n"
  • byte buf str.getBytes()
  • out.write(buf)
  • while( (cin.read())! -1 )
  • System.out.print((char) c)

55
Class ServerSocket (1)
  • Creates a Socket for each client connection
  • The server then can handle these connections in
    the usually manner, typically by extracting the
    InputStream and an OutputStream and communicating
    with the client through the stream interface

ServerSocket
port
Socket
56
Class ServerSocket (2)
  • Constructors
  • ServerSocket(int port)
  • Some methods
  • Socket accept()
  • void close()
  • InetAddress getInetAddress()
  • int getLocalPort()

57
Class Diagram of HTTPServerDemo
58
HTTPServerDemo (1)
  • import java.io.
  • import java.net.
  • import java.util.StringTokenizer
  • import java.util.Date
  • public class HTTPServerDemo
  • static final int PORT 8080 public static
    void main(
  • String args)
  • ServerSocket serverConnect
  • null

59
HTTPServerDemo (2)
  • try
  • serverConnect new
  • ServerSocket(PORT)
  • System.out.println(
  • "\nListening for
  • connections on port
  • PORT "...\n")
  • while (true)
  • HttpServer server new
  • HttpServer(
  • serverConnect.accept())

60
HTTPServerDemo (3)
  • catch (IOException e)
  • System.out.println(
  • "Connection error " e )

61
HTTPServerDemo (4)
  • class HttpServer implements Runnable
  • static final File WEB_ROOT new
  • File(".")
  • static final String DEFAULT_FILE
  • "index.html"
  • Socket connect
  • public HttpServer(Socket connect)
  • this.connect connect

62
HTTPServerDemo (5)
  • Thread threadRunner new
  • Thread(this)
  • threadRunner.start()
  • public void run()
  • try
  • BufferedReader in new
  • BufferedReader( new InputStreamReader
    (
  • connect.getInputStream()))

63
HTTPServerDemo (6)
  • PrintWriter out new
  • PrintWriter(
  • connect.getOutputStream())
  • String input in.readLine()
  • StringTokenizer parse new
  • StringTokenizer(input)
  • String method
  • parse.nextToken().
  • toUpperCase()
  • String fileRequested
  • parse.nextToken().
  • toLowerCase()

64
HTTPServerDemo (7)
  • if (!method.equals("GET"))
  • sendStatus( out, 501,
  • "Not Implemented", method )
  • else
  • doGet( fileRequested, out )
  • connect.close()

65
HTTPServerDemo (8)
  • catch (IOException e)
  • System.err.println(
  • "Server Error " e)
  • private void doGet(
  • String fileRequested,
  • PrintWriter out )

66
HTTPServerDemo (9)
  • if
  • (fileRequested.endsWith("/"))
  • fileRequested
  • DEFAULT_FILE
  • try
  • File file new
  • File(WEB_ROOT, fileRequested)
  • int fileLength
  • (int)file.length()

67
HTTPServerDemo (10)
  • String content
  • getContentType(fileRequested)
  • out.println(
  • "HTTP/1.0 200 OK")
  • out.println(
  • "Server HttpServer 1.0")
  • out.println("Date " new
  • Date())
  • out.println(
  • "Content-type " content)
  • out.println(
  • "Content-length " file.length())

68
HTTPServerDemo (11)
  • out.println()
  • out.flush()
  • FileInputStream fileIn
  • new FileInputStream(file)
  • byte fileData new
  • bytefileLength
  • fileIn.read(fileData)
  • fileIn.close()
  • BufferedOutputStream
  • dataOut new
  • BufferedOutputStream(
  • connect.getOutputStream())

69
HTTPServerDemo (12)
  • dataOut.write(fileData, 0, fileLength)
  • dataOut.flush()
  • dataOut.close()
  • catch (IOException e)
  • sendStatus(out, 404,
  • "File Not Found", fileRequested)

70
HTTPServerDemo (13)
  • private void sendStatus( PrintWriter out,
  • int code, String status,
  • String msg )
  • out.println("HTTP/1.0 " code
  • " " status )
  • out.println(
  • "Server HttpServer 1.0")
  • out.println("Date "
  • new Date())
  • out.println(
  • "Content-Type text/html")

71
HTTPServerDemo (14)
  • out.println()
  • out.println("ltHTMLgt")
  • out.println("ltHEADgtltTITLEgt"
  • status "lt/TITLEgtlt/HEADgt")
  • out.println("ltBODYgt")
  • out.println("ltH2gt" code " " status
    " " msg "lt/H2gt")
  • out.println("lt/BODYgt")
  • out.println("lt/HTMLgt")

72
HTTPServerDemo (15)
  • private String getContentType(
  • String fileRequested )
  • if (fileRequested.endsWith(".htm")
    fileRequested.endsWith(".html"))
  • return "text/html"
  • else
  • return "text/plain"

73
Class Class (1)
  • Included in package java.lang
  • Instances represent classes and interfaces in a
    running Java application
  • No public constructors
  • Constructed automatically by the Java Virtual
    Machine as classes are loaded and by calls to the
    defineClass method in the class loader

74
Class Class (2)
  • Some methods
  • static Class forName(
  • String className)
  • Constructor getConstructor(
  • Class paramType)
  • Constructor getConstructors()
  • Field getField(String name)
  • Method getMethod(String name, Class paramType)
  • Method getMethods()
  • Object newInstance()

75
Package java.lang.reflect
  • Used to obtain runtime class information
  • Some classes in the package
  • Constructor
  • Field
  • Method
  • Modifier
  • ReflectPermission

76
Class Modifier
  • Provides static methods and constants to decode
    class modifiers
  • Some static int constants
  • ABSTRACT
  • PRIVATE
  • PROTECTED
  • PUBLIC
  • STATIC
  • FINAL
  • INTERFACE
  • SYNCHRONIZED

77
Class Constructor
  • Provides information about, and access, to, a
    single constructor for a class
  • Some methods
  • String getName()
  • int getModifiers()
  • Class getParameterTypes()
  • Object newInstance(
  • Object initArgs )

78
Class Field
  • Provides information about, and dynamic access
    to, a single field of a class or an interface
  • Some methods
  • Object get(Object obj)
  • int getModifiers()
  • String getName()
  • Class getType()
  • void set(Object obj,
  • Object value)

79
Class Method
  • Provides information about, and access to, a
    single method on a class or an interface
  • Some methods
  • int getModifiers()
  • String getName()
  • Class getParameterTypes()
  • Class getReturnType()
  • Object invoke(Object obj,
  • Object args)

80
Class ClassLoader (1)
  • An abstract class
  • A class loader is responsible for loading classes
  • Given the name of a class, a class loader should
    locate or generate data that constitutes the
    definition for the class
  • A typical strategy is to transform the name into
    a file name and read a class file of the name
    from a file system
  • Every Class object contains a reference to the
    ClassLoader that defined it

81
Class ClassLoader (2)
  • Some methods
  • Class loadClass(String name)
  • protected Class defineClass(String name,
  • byte b, int off, int length)
  • protected Class findClass(String name)
  • protected Class findLoadedClass(String name)

82
ClassLoaderDemo (1-1)
  • import java.io.
  • public class TestClass implements Serializable
  • int i
  • public TestClass()
  • try
  • System.out.println("Constructor")
  • i 1
  • catch (Exception e)
  • System.out.println(e)

83
ClassLoaderDemo (1-2)
  • public void Show()
  • System.out.println("TestClass")
  • public int getI()
  • return i
  • public void increaseI( int inc )
  • i inc

84
ClassLoaderDemo (2-1)
  • import java.io.
  • import java.lang.reflect.Method
  • class TestLoader extends ClassLoader
  • public Class findClass(
  • String name )
  • byte b loadClassData(name)
  • System.out.println(
  • "data loaded")
  • return defineClass(name,
  • b, 0, b.length)

85
ClassLoaderDemo (2-2)
  • private byte loadClassData(String name)
  • byte code new byte1024
  • try
  • File codeFile new File(
  • "C\\My Documents\\
  • jbproject\\ClassLoaderDemo\\
  • classes\\TestClass",
  • "TestClass.class" )
  • FileInputStream cis new
  • FileInputStream( codeFile )
  • int nBytes cis.read( code )

86
ClassLoaderDemo (2-3)
  • System.out.println(
  • "nBytes "nBytes)
  • catch ( Exception e )
  • System.out.println( e )
  • return code

87
ClassLoaderDemo (2-4)
  • public class ClassLoaderDemo
  • public static void main(
  • String args )
  • try
  • ClassLoader loader new
  • TestLoader()
  • Class testClass
  • loader.loadClass(
  • "TestClass.TestClass")
  • Object test
  • testClass.newInstance()

88
ClassLoaderDemo (2-5)
  • Method testMethod
  • testClass.getMethods()
  • int nMethods
  • testMethod.length
  • System.out.println(
  • "number of methods "
  • nMethods )
  • for(int i0 iltnMethods i)
  • String name
  • testMethodi.getName()
  • System.out.println(
  • "Method " i " " name )

89
ClassLoaderDemo (2-6)
  • Method methodShow
  • testMethod10
  • Object param null
  • Object invoke
  • methodShow.invoke( test,
  • param )
  • Method increaseI
  • testMethod9
  • Integer incObj new Integer(5)
  • param new Object1
  • param0 incObj
  • Object increaseIInvoke increaseI.invoke(
    test, param )

90
ClassLoaderDemo (2-7)
  • Method methodGetI
  • testMethod11
  • param null
  • Object returnedI methodGetI.invoke( test,
    param )
  • Integer iWrapper (Integer)
  • returnedI
  • System.out.println(
  • "returned i "
  • iWrapper.intValue() )
  • catch ( Exception e )
  • System.out.println( e )

91
ObjectSerializationDemo (1-1)
  • import testclass.
  • import java.io.
  • class MyObjectOutputStream extends
    ObjectOutputStream
  • public MyObjectOutputStream(
  • OutputStream out )
  • throws IOException
  • super( out )

92
ObjectSerializationDemo (1-2)
  • protected void annotateClass(
  • Class cl) throws IOException
  • super.annotateClass(cl)
  • // Serialize byte code address
  • String fileName
  • "C\\My Documents" "\\jbproject"
    "\\ObjectSerializationDemo"
  • "\\classes""\\testclass
  • "\\TestClass.class"

93
ObjectSerializationDemo (1-3)
  • int nChar fileName.length()
  • writeInt( nChar )
  • System.out.println(nChar)
  • for(int i0 iltnChar i)
  • writeChar( fileName.charAt(i) )
  • System.out.print(
  • fileName.charAt(i) )

94
ObjectSerializationDemo (1-4)
  • public class ObjectSerializationDemo
  • public static void main(
  • String args )
  • try
  • FileOutputStream fos new
  • FileOutputStream("serial")
  • MyObjectOutputStream oos
  • new
  • MyObjectOutputStream(fos)
  • TestClass test new
  • TestClass()

95
ObjectSerializationDemo (1-5)
  • oos.writeObject(test)
  • oos.flush()
  • oos.close()
  • catch(Exception e)
  • System.out.println(
  • "Exception during serialization "e)
  • System.exit(0)

96
ObjectDeserializationDemo (1-1)
  • import java.io.
  • import java.lang.reflect.Method
  • // load from an address
  • class MyLoader extends ClassLoader
  • String fileName
  • public MyLoader( String fileName )
  • this.fileName fileName

97
ObjectDeserializationDemo (1-2)
  • public Class loadClass(
  • String name )
  • throws ClassNotFoundException
  • return super.loadClass( name )
  • public Class findClass(
  • String name )
  • byte b loadClassData(name)
  • return defineClass(name, b, 0, b.length)

98
ObjectDeserializationDemo (1-3)
  • private byte loadClassData(
  • String name)
  • byte code null
  • try
  • File codeFile new
  • File( fileName )
  • FileInputStream cis new
  • FileInputStream( codeFile )
  • int fileLength (int)
  • codeFile.length()
  • code new bytefileLength
  • int nBytes cis.read( code )

99
ObjectDeserializationDemo (1-4)
  • System.out.println(
  • "nBytes "nBytes)
  • catch ( Exception e )
  • System.out.println( e )
  • return code

100
ObjectDeserializationDemo (1-5)
  • class MyObjectInputStream extends
    ObjectInputStream
  • public MyObjectInputStream(
  • InputStream in )
  • throws IOException
  • super(in)

101
ObjectDeserializationDemo (1-6)
  • protected Class resolveClass(ObjectStreamClass
    v)
  • throws IOException
  • int nChar readInt()
  • System.out.println( nChar )
  • char fName new charnChar
  • for(int i0 iltnChar i)
  • fNamei readChar()
  • System.out.print( fNamei )
  • System.out.println()

102
ObjectDeserializationDemo (1-7)
  • String fileName new
  • String( fName )
  • System.out.println( fileName )
  • MyLoader myLoader new
  • MyLoader( fileName )
  • Class myClass null
  • try
  • String name v.getName()
  • myClass
  • myLoader.loadClass( name )

103
ObjectDeserializationDemo (1-8)
  • catch ( ClassNotFoundException e )
  • System.out.println( e )
  • return myClass

104
ObjectDeserializationDemo (1-9)
  • public class ObjectDeserializationDemo
  • public static void main(
  • String args )
  • try
  • FileInputStream fis new
  • FileInputStream( "serial" )
  • MyObjectInputStream ois new
  • MyObjectInputStream( fis )
  • Object test
  • ois.readObject()
  • ois.close()

105
ObjectDeserializationDemo (1-10)
  • Class testClass test.getClass()
  • Method testMethod
  • testClass.getMethods()
  • int nMethods
  • testMethod.length
  • System.out.println(
  • "number of methods
  • nMethods )
  • for(int i0 iltnMethods i)
  • String name
  • testMethodi.getName()

106
ObjectDeserializationDemo (1-11)
  • System.out.println( "Method " i " "
    name )
  • Method methodShow
  • testMethod10
  • Object param null
  • Object invoke
  • methodShow.invoke( test, param )
  • Method increaseI
  • testMethod9
  • Integer incObj new
  • Integer(5)

107
ObjectDeserializationDemo (1-12)
  • param new Object1
  • param0 incObj
  • Object increaseIInvoke increaseI.invoke(
    test, param )
  • Method methodGetI
  • testMethod11
  • param null
  • Object returnedI methodGetI.invoke( test,
    param )
  • Integer iWrapper
  • (Integer) returnedI

108
ObjectDeserializationDemo (1-13)
  • System.out.println(
  • "returned i "
  • iWrapper.intValue() )
  • catch( Exception e )
  • System.out.println(
  • "Exception during deserialization "
  • e )
  • System.exit(0)

109
ObjectSerializationDemo (2-1)
  • class MyObjectOutputStream extends
    ObjectOutputStream
  • public MyObjectOutputStream(
  • OutputStream out )
  • throws IOException
  • super( out )
  • protected void annotateClass(Class cl) throws
    IOException
  • super.annotateClass(cl)

110
ObjectSerializationDemo (2-2)
  • // Serialize byte code
  • byte code null
  • try
  • File codeFile new File(
  • "C\\My Documents"
  • "\\jbproject"
  • "\\ObjectSerializationDemo"
  • "\\classes"
  • "\\testclass"
  • "\\TestClass.class" )
  • int fileLength (int)
  • codeFile.length()

111
ObjectSerializationDemo (2-3)
  • writeInt( fileLength )
  • code new bytefileLength
  • FileInputStream cis new
  • FileInputStream( codeFile )
  • int nBytes cis.read( code )
  • write( code )
  • System.out.println(
  • "nBytes "nBytes)
  • catch ( Exception e )
  • System.out.println( e )
  • write( code )

112
ObjectDeserializationDemo (2-1)
  • // load from byte code
  • class MyLoader extends ClassLoader
  • int codeLength
  • byte code
  • public MyLoader( int n,
  • byte code )
  • codeLength n
  • this.code new
  • bytecodeLength
  • this.code code

113
ObjectDeserializationDemo (2-2)
  • public Class loadClass(
  • String name )
  • throws ClassNotFoundException
  • return super.loadClass( name )
  • public Class findClass( String name )
  • return defineClass(name, code, 0,
    codeLength)

114
ObjectDeserializationDemo (2-3)
  • class MyObjectInputStream extends
    ObjectInputStream
  • public MyObjectInputStream(
  • InputStream in )
  • throws IOException
  • super(in)
  • protected Class resolveClass(ObjectStreamClass
    v)
  • throws IOException
  • int n readInt()

115
ObjectDeserializationDemo (2-4)
  • System.out.println(
  • "number of bytes " n )
  • byte code new byten
  • read( code )
  • MyLoader myLoader new
  • MyLoader( n, code )
  • Class myClass null
  • try
  • String name v.getName()
  • myClass
  • myLoader.loadClass( name )

116
ObjectDeserializationDemo (2-5)
  • catch (
  • ClassNotFoundException e )
  • System.out.println( e )
  • return myClass

117
Package java.rmi
  • Allows Java objects residing in different virtual
    machines to communicate using normal method calls

client JVM
server JVM
Remote
RemoteObject
method()
method()
Internet
stub
stub
118
Interface Remote
  • To identify interfaces whose methods can be
    invoked on a non-local machine
  • No methods defined
  • Only methods specified in interfaces that extend
    this interface are available remotely

119
Generates Stubs
  • Stub classes for a class which implements the
    Remote interface will be generated with the rmic
    tool
  • Stub classes contain all the code involved in
    serializing details of a remote method call,
    dynamically invoking the remote method and
    serializing the results back to the caller

120
Distributing Codes
  • Server-side Classes
  • Interfaces that extend interface Remote
  • Implementation of the interface (server classes)
  • Stub classes
  • Client-side Classes
  • Interfaces that extend interface Remote
  • Stub classes
  • Client classes

121
Naming Registry
  • Clients can invoke methods on remote objects only
    if they have a reference to the object
  • RMI registry is provided for obtaining such a
    reference

122
Start RMI Registry
  • Run DOS
  • Set CLASSPATHC\MYDOCU1\
  • jbproject\RMIServer\classes
  • cd C\JBuilder4\jdk1.3\bin
  • start rmiregistry

123
RMIServer (1)
  • import java.rmi.
  • public interface AddServerIntf extends Remote
  • double add(double d1, double d2) throws
    RemoteException

124
RMIServer (2)
  • import java.rmi.
  • import java.rmi.server.
  • public class AddServerImpl extends
    UnicastRemoteObject
  • implements AddServerIntf
  • public AddServerImpl() throws RemoteException
  • public double add(double d1, double d2) throws
    RemoteException
  • return d1 d2

125
RMIServer (3)
  • import java.net.
  • import java.rmi.
  • public class AddServer
  • public static void main(
  • String args)
  • try
  • AddServerImpl addServerImpl
  • new AddServerImpl()
  • Naming.rebind("AddServer",
  • addServerImpl)
  • catch (Exception e)
  • System.out.println(
  • "Exception "e)

126
RMIClient (1)
  • import java.rmi.
  • import rmiserver.
  • public class RMIClient
  • public static void main(
  • String args)
  • try
  • String addServerURL
  • "rmi//localhost/AddServer"
  • AddServerIntf addServerIntf
  • (AddServerIntf)
  • Naming.lookup(addServerURL)

127
RMIClient (2)
  • System.out.println(
  • "The sum is "
  • addServerIntf.add(4, 7))
  • catch (Exception e)
  • System.out.println(
  • "Exception "e)
Write a Comment
User Comments (0)
About PowerShow.com