Download Networking Issues in Java

Document related concepts
no text concepts found
Transcript
Algorithm Programming 2
89-211
Network Programming
Bar-Ilan University
2005-2006 ‫תשס"ו‬
by Moshe Fresko
Networking Basics

Uses of Networks





Resource Sharing
High Reliability
Saving Money
Communication Medium
Access to remote information
Network Layers
Application Layer (http,ftp,telnet,smtp,dns,…)
Transport Layer (TCP,UDP,…)
Network Layer (IP,…)
Physical + Data Link Layer (Arpanet,SatNet,Lan, …)
TCP vs UDP

TCP : Transmission Control Protocol : Is a connection- based protocol
that provides a reliable flow of data between two computers.





Used when two applications want to communicate reliably
It is Connection Based
Data is get in the same order it was sent (via Streams)
Transmission guarantied, or error is reported.
Example:


HTTP, FTP, SMTP, TELNET,
UDP : User Datagram Protocol : Is a protocol that sends independent
packets of data, called datagrams, from one computer to another with
no guarantees about arrival.





Not connection based
Communication is not guaranteed
Datagram : A packet sent by UDP protocol.
The order of datagrams are not guaranteed.
Example:

Radio, Clock Server, Ping,
IP Address


IP (Internet Protocol) : Network layer protocol.
IP Address : A unique 32 bit number.




Every host and router in the Internet has an IP address, which
encodes its network number and host number.
Classes of IP Addresses






Dotted Decimal Notation : 192.41.6.20
Range : 0.0.0.0 – 255.255.255.255
Class
Class
Class
Class
Class
A : 0{7 bits Network}.{24 bits Host}
B : 10{14 bits Network}.{16 bits Host}
C : 110{21 bits Network}.{8 bits Host}
D : 1110{Multicast address}
E : 11110{Reserved for future use}
Special IP-addresses



0.0.0.0 : This host
255.255.255.255 : Broadcast on local network
127.?.?.? : Loopback
Ports



Generally a computer has a single physical
connection to the network.
The data can be intended to different applications
Port: A unique place within the machine.
(Abstraction)


16 bit number
Well-known ports: 0..1023 are reserved ports



FTP is 21, TELNET 23, SMTP 25, HTTP 80, POP
Custom Use > 1024
The TCP and UDP protocols use ports to map
incoming data to a particular process running on a
computer
URLs


URL : Uniform Resource Locater : It is a reference
(an address) to a resource on the Internet.
A URL has two main components



Example : http://java.sun.com/



Protocol Identifier
Resource Name
http : is the Protocol Identifier
//java.sun.com/ : is the Resource Name
The Resource Name may contain




HostName : The name of the machine
FileName : The pathname of the file on the machine
Port Number : The port number to which to connect
(Typically Optional)
Reference : A reference to a named anchor within a
resource (Typically Optional)
URLs

Two classes for URL processing in Java



java.net.URL : Represents a URL resource
java.net.URLConnection : An opened connection to a URL resource
Creating an absolute URL object



Creating a URL relative to another




By Constructor : URL(String)
URL myurl = new URL(“http://cs.biu.ac.il/”) ;
Used for relative hyperlinks in an HTML page
<A HREF=“MyPres.html”>Presentations</A>
By Constructor : URL(URL,String)
URL myurl = new URL(“http://cs.biu.ac.il/~freskom1/”) ;
URL mypres = new URL(myurl, “MyPres.html”) ;
Other URL Constructors

All constructors throw MalformedURLException




URL(String protocol, String host, int port, String file)
URL(String protocol, String host, String file)
URL(String spec)
URL(URL context, String spec)
URLs

Parsing a URL
String getProtocol()
String getFile()

Example
String getHost()
String getRef()
int getPort()
import java.net.* ;
public class ParseURL {
public static void main(String[]args) throws
MalformedURLException {
URL url = new URL("http://java.sun.com:80/docs/”+
”books/tutorial/intro.html#DOWNLOADING") ;
System.out.println("Protocol = "+url.getProtocol()) ;
System.out.println("Host
= "+url.getHost()) ;
System.out.println("FileName = "+url.getFile()) ;
System.out.println("Port
= "+url.getPort()) ;
System.out.println("Reference= "+url.getRef()) ;
}
}

Output
Protocol =
Host
=
FileName =
Port
=
Reference=
http
java.sun.com
/docs/books/tutorial/intro.html
80
DOWNLOADING
URLs

Reading directly from a URL using openStream() method that
returns an InputStream

Example:
import java.net.* ;
import java.io.* ;
public class URLReader {
public static void main(String[] args) throws Exception {
URL url = new URL("http://www.cs.biu.ac.il/~freskom1/") ;
BufferedReader br = new BufferedReader (
new InputStreamReader(url.openStream())) ;
String line ;
while ((line=br.readLine())!=null)
System.out.println(line) ;
br.close() ;
}
}
URL Connection

Connecting to a URL

URL’s openConnection() method
URLConnection openConnection() throws IOException ;

Example:
try {
URL url = new URL("http://www.cs.biu.ac.il/~freskom1/") ;
URLConnection uc = url.openConnection() ;
}
catch (MalformedURLException e) { … }
catch (IOException e) { … }

Reading from a URL connection
import java.net.* ;
import java.io.* ;
public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL url = new URL("http://www.cs.biu.ac.il/~freskom1/") ;
URLConnection uc = url.openConnection() ;
BufferedReader br=new BufferedReader(new InputStreamReader(uc.getInputStream()));
String line ;
while ((line=br.readLine())!=null)
System.out.println(line) ;
br.close() ;
}}
Writing to a URLConnection

Like HTML forms.




In the Browser, Text fields and other GUI components that let user enter data.
Browser writes the data to the URL.
On the server a CGI-BIN script processes it and returns a response.
Example:
import java.io.* ;
import java.net.* ;
public class Reverse {
public static void main(String[]args) throws Exception {
if (args.length<1)
{ System.err.println("Usage: java Reverse <String>") ; System.exit(1) ; }
String stringToReverse = URLEncoder.encode(args[0],"UTF-8") ;
URL url = new URL("http://java.sun.com/cgi-bin/backwards") ;
URLConnection uc = url.openConnection() ; uc.setDoOutput(true) ;
PrintWriter out = new PrintWriter(uc.getOutputStream()) ;
out.println("string="+stringToReverse) ;
out.close() ;
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream())) ;
String line ;
while ((line=in.readLine())!=null)
System.out.println(line) ;
}}
Sockets




Socket: End point of a two-way communication link
between two programs running on the network.
Socket is a software abstraction to represent the
“terminals” of a connection.
A socket is bound to a port number so that the TCP
layer can identify the application that data is destined
to be sent.
Two stream-based Socket classes

ServerSocket : For server


On connection returns a new Socket
Socket : For client

Have getInputStream() and getOutputStream() functions
Socket Example – Echo
import java.io.* ;
import java.net.* ;
public class EchoClient {
public static void main(String[]args) throws IOException {
Socket socket = null ;
PrintWriter out = null ;
BufferedReader in = null ;
String host = "localhost" ;
try {
socket = new Socket(host,7) ;
// Port number 7
out = new PrintWriter(socket.getOutputStream(),true) ;
in = new BufferedReader(new InputStreamReader(socket.getInputStream())) ;
} catch (UnknownHostException e) {
System.err.println("Dont know host: "+host) ; System.exit(-1) ;
} catch (IOException e) {
System.err.println("Cannot get IO for connection to "+host) ; System.exit(-1) ;
}
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)) ;
String input ;
while ((input=stdin.readLine())!=null) {
out.println(input) ;
System.out.println("echo: "+in.readLine()) ;
}
out.close() ; in.close() ; stdin.close() ; socket.close() ;
// Order important
} }
Socket Connection for Client
Basic program flow for Client

1.
2.
3.
4.
5.
–
Open Socket
Open an input stream and output stream to the
socket
Read from and write to the stream according to
the server’s protocol
Close the streams
Close the socket
Only step 3 differs from client to client,
depending on the server
Socket Connection for Server
Basic program flow for Server

1.
2.
3.
4.
5.
6.
7.

Create a ServerSocket
Call ServerSocket.accept() to get a Socket connection
Open input stream and output stream to that socket
Read from and write to streams according to the Protocol
Close the streams
Close the socket
( Optional: Return to 2 to get another connection )
For Server allowing multiple connections, 3-6 must be in
another thread
Example: Knock Knock

Example, the Knock Knock jokes
Server
Client
Server
Client
Server

Classes:
:
:
:
:
:
“Knock! Knock!”
“Who’s there?”
“Dexter”
“Dexter who?”
“Dexter halls with boughs of holly”
KnockKnockProtocol : To implement the protocol
KnockKnockServer : Has main method for the Server and
listens to the port
KnockKnockClient : Connects to the server
KnockKnockProtocol
import java.net.* ;
import java.io.* ;
public class KnockKnockProtocol {
private static final int WAITING = 0 , SENTKNOCKKNOCK = 1 , SENTCLUE = 2 , ANOTHER = 3 ;
private static final int NUMJOKES = 5 ;
private int state = WAITING ;
private int currentJoke = 0 ;
private String[] clues = { "Turnip", "Little Old Lady", "Atch", "Who", "Who" } ;
private String[] answers = { "Turnip the heat, it's cold in here", "I didn't know you could yodel!", "Bless you!", "Is there an owl here?", "Is there an echo in
here?" } ;
public String processInput(String theInput) {
String theOutput=null;
if (state==WAITING) {
theOutput="Knock! Knock!" ; state = SENTKNOCKKNOCK ;
} else if (state==SENTKNOCKKNOCK) {
if (theInput.equalsIgnoreCase("Who's there?"))
{ theOutput = clues[currentJoke] ; state = SENTCLUE ; }
else { theOutput = "You're supposed to say 'Who's there?' Try again. Knock! Knock!" ; }
} else if (state==SENTCLUE) {
if (theInput.equalsIgnoreCase(clues[currentJoke]+" who?"))
{ theOutput = answers[currentJoke] + " Want another? (y/n)" ; state = ANOTHER ; }
else { theOutput = "You're supposed to say '"+clues[currentJoke]+" who?'"+" ! Try again. Knock! Knock!" ; state = SENTKNOCKKNOCK ; }
} else if (state==ANOTHER) {
if (theInput.equalsIgnoreCase("y")) {
theOutput = "Knock! Knock!" ;
if ((++currentJoke)==NUMJOKES)
currentJoke=0 ;
state = SENTKNOCKKNOCK ;
} else { theOutput = "Bye." ; state = WAITING ; }
}
return theOutput ;
}}
KnockKnockServer
import java.net.* ;
import java.io.* ;
public class KnockKnockServer
{
public static void main(String[]args) throws IOException {
ServerSocket serverSocket = null ;
try { serverSocket = new ServerSocket(4444) ; }
catch (IOException e) { System.err.println("Cannot listen on port 4444") ; System.exit(-1) ; }
Socket clientSocket = null ;
try { clientSocket = serverSocket.accept() ; }
catch (IOException e) { System.err.println("Accept failed") ; System.exit(-1) ; }
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),true) ;
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())) ;
String inputLine, outputLine ;
KnockKnockProtocol kkp = new KnockKnockProtocol() ;
outputLine = kkp.processInput(null) ;
out.println(outputLine) ;
while((inputLine=in.readLine())!=null) {
outputLine = kkp.processInput(inputLine) ;
out.println(outputLine) ;
if (outputLine.equals("Bye.")) break ;
}
out.close() ; in.close() ;
clientSocket.close() ; serverSocket.close() ;
}}
KnockKnockClient
import java.io.* ;
import java.net.* ;
public class KnockKnockClient {
public static void main(String[]args) throws IOException {
Socket kkSocket = null ; PrintWriter out = null ; BufferedReader in = null ;
try {
kkSocket = new Socket("localhost",4444) ;
out = new PrintWriter(kkSocket.getOutputStream(),true) ;
in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream())) ;
}
catch (UnknownHostException e) { System.err.println("Don't know about host: localhost") ; System.exit(-1) ; }
catch (IOException e) { System.err.println("Cannot get IO for the connection to: localhost") ; System.exit(-1) ; }
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in)) ;
String fromServer, fromUser ;
while ((fromServer=in.readLine())!=null) {
System.out.println("Server: "+fromServer) ;
if (fromServer.equals("Bye.")) break ;
fromUser = stdin.readLine() ;
if (fromUser!=null) {
System.out.println("Client: "+fromUser) ;
out.println(fromUser) ;
}}
out.close() ; in.close() ; stdin.close() ; kkSocket.close() ;
} }

KnockKnock
Run
Server Side
E:\>java KnockKnockServer

Client Side
E:\>java KnockKnockClient
Server: Knock! Knock!
who is?
Client: who is?
Server: You're supposed to say 'Who's there?' Try again. Knock! Knock!
Who's there?
Client: Who's there?
Server: Turnip
Turnip who?
Client: Turnip who?
Server: Turnip the heat, it's cold in here Want another? (y/n)
n
Client: n
Server: Bye.
Supporting Multiple Clients

In the Server Side
while (true) {
accept a connection ;
create a thread to deal with the client ;
}
Server Thread - KKMultiServerThread
import java.net.* ;
import java.io.* ;
public class KKMultiServerThread extends Thread {
private Socket socket = null ;
public KKMultiServerThread(Socket socket) {
this.socket = socket ;
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())) ;
PrintWriter out = new PrintWriter(socket.getOutputStream(),true) ;
String inputLine, outputLine ;
KnockKnockProtocol kkp = new KnockKnockProtocol() ;
outputLine = kkp.processInput(null) ;
out.println(outputLine) ;
while ((inputLine=in.readLine())!=null) {
outputLine = kkp.processInput(inputLine) ;
out.println(outputLine) ;
if (outputLine.equals("Bye."))
break ;
}
out.close() ; in.close() ; socket.close() ;
} catch (IOException e) { e.printStackTrace() ; }
} }
Server Class - KKMultiServer
import java.net.* ;
import java.io.* ;
public class KKMultiServer {
public static void main(String[]args) throws IOException {
ServerSocket serverSocket = null ;
boolean listening = true ;
try {
serverSocket = new ServerSocket(4444) ;
} catch (IOException e) {
System.err.println("Could not listen on port 4444") ;
System.exit(-1) ;
}
while (listening)
new KKMultiServerThread(serverSocket.accept()).start() ;
serverSocket.close() ;
}
}
Remote Connections
Identifying a Machine


IP (Internet Protocol) adress
1.
2.

DNS (Domain Name System) : www.cs.biu.ac.il
Dotted Quad Form : 123.255.28.120
InetAddress ia=InetAddress.getByName(…);
Local Host (for testing)


All these three forms connect to local host




InetAddress
InetAddress
InetAddress
InetAddress
ia=InetAddress.getByName(null) ;
ia=InetAddress.getByName(“localhost”);
ia=InetAddress.getByName(“127.0.0.1”);
ia=InetAddress.getLocalHost()
Identifying a Machine
import java.net.*;
public class WhoAmI {
public static void main(String[] args) throws Exception {
if(args.length != 1) {
System.err.println("Usage: WhoAmI MachineName");
System.exit(1);
}
InetAddress a = InetAddress.getByName(args[0]);
System.out.println(a);
}
}
To run:
java WhoAmI myMachine
myMachine/127.0.0.1
UDP communication


UDP : Delivers independent packages whose
arrival and order of arrival is not guaranteed.
Packets sent by UDP protocol are called
Datagrams.


DataGram : Is an independent, self-contained
message sent over the network whose arrival, and
content are not guaranteed.
Classes for UDP connection



DatagramPacket
DatagramSocket
MulticastSocket
DatagramPacket class

Constructors







DatagramPacket(byte
DatagramPacket(byte
DatagramPacket(byte
DatagramPacket(byte
DatagramPacket(byte
DatagramPacket(byte
Methods












buf[],
buf[],
buf[],
buf[],
buf[],
buf[],
int
int
int
int
int
int
offset, int length)
length)
offset, int length, InetAddress address, int port)
offset, int length, SocketAddress address)
length, InetAddress address, int port)
length, SocketAddress address)
void setAddress(InetAddress iaddr)
InetAddress getAddress()
void setSocketAddress(SocketAddress address)
SocketAddress getSocketAddress()
void setPort(int iport)
int getPort()
byte[] getData()
int getOffset()
int getLength() {
void setData(byte[] buf, int offset, int length)
void setData(byte[] buf)
void setLength(int length)
Example: Quote Server - Client

QuoteServer




QuoteClient



Waits to get a DataGram
Reads the next line from file “lines.txt”
Sends it as a DataGram
Sends a DataGram to Server
Listens to the Server for getting a DataGram with the Quote
Lines.txt file
Quote
Quote
Quote
Quote
…

Run:




number
number
number
number
1.
2.
3.
4.
E:\>java QuoteClient localhost
Received: Quote number 1.
E:\>java QuoteClient localhost
Received: Quote number 2.
Example : QuoteServer
import java.io.* ;
import java.net.* ;
import java.util.* ;
public class QuoteServer {
protected DatagramSocket socket = null ;
protected BufferedReader in = null ;
protected boolean moreQuotes = true ;
public void run() throws IOException {
socket = new DatagramSocket(4445) ;
while (moreQuotes) {
try {
byte[] buf = new byte[256] ;
// Request
DatagramPacket packet = new DatagramPacket(buf,buf.length) ;
socket.receive(packet) ;
// Response
String response = getNextQuote() ;
buf = response.getBytes() ;
// Send the response
InetAddress address = packet.getAddress() ;
int port = packet.getPort() ;
packet = new DatagramPacket(buf,buf.length,address,port) ;
socket.send(packet) ;
} catch(IOException e) {
e.printStackTrace() ;
moreQuotes = false ;
} }
socket.close() ;
}
public QuoteServer() {
try { in = new BufferedReader(new FileReader("lines.txt")) ;
} catch (IOException e) { System.err.println("Cannot open file
lines.txt.") ; }
}
public String getNextQuote() {
String retVal = null ;
if (in==null) {
retVal = "Error in opening file." ;
moreQuotes = false ;
} else {
try {
if ((retVal=in.readLine())==null) {
in.close() ;
retVal = "No more quotes." ;
moreQuotes = false ;
}
} catch (IOException e) {
retVal = "Exception in server." ;
moreQuotes = false ;
}
}
return retVal ;
}
public static void main(String[]args) throws IOException {
QuoteServer qs = new QuoteServer() ;
qs.run() ;
}
}
Example: QuoteClient
import java.io.* ;
import java.net.* ;
import java.util.* ;
public class QuoteClient {
public static void main(String[]args) throws IOException {
if (args.length!=1) {
System.err.println("Usage: java QuoteClient hostname") ;
return ;
}
DatagramSocket socket = new DatagramSocket() ;
byte[] buf=new byte[256] ;
InetAddress address = InetAddress.getByName(args[0]) ;
DatagramPacket packet = new DatagramPacket(buf,buf.length,address,4445) ;
socket.send(packet) ;
packet=new DatagramPacket(buf,buf.length) ;
socket.receive(packet) ;
}
String received=new String(packet.getData()) ;
System.out.println("Received: "+received) ;
socket.close() ;
SMTP : Sending e-mail

SMTP : Simple Mail Transfer Protocol



A client delivers mail using a mail-server by opening a socket
(TCP) connection to port 25 of it.
Once the connection is made, the client sends some
commands for sending e-mail messages
For each command, Server sends back a message
starting with a number



Numbers 200-299: A successful command
Numbers 300-399: Initially successful, but more information
needed to complete it.
Numbers 400-499,500-599: Error

SMTP
Commands
SMTP Commands




HELO : Greeting from the client to server
MAIL FROM: sender’s address
RCPT TO: recipient address
DATA



To read the message one line at a time.
“.” to end the message
Example session (may be with telnet connection)
HELO
250 ….
MAIL FROM: bill
250 bill… sender ok
RCPT TO: mark
250 mark… Recipient ok
DATA
354 Enter main, end with “.” on a line by itself
Subject: Hey there…
This is a trial message
.
250 VAA07456 Message accepted for delivery
POP3 protocol

POP3 : Post Office Protocol version 3.


Allows you to access your mailbox remotely
Responses start with





‘+’ for successful commands
‘-’ in case of any error
Sometimes it returns multi-line responses, that terminate
with “.” line.
Usually it sits on port number 110.
POP3 logging


USER your_user_name
PASS your_password
POP3 commands

POP3 access commands






STAT : Retrieves the message count
LIST : Gets a list of active message numbers
TOP : To examine the beginning of a message
RETR : To read an entire message
DELE : To delete a message
Example: (Telnet session)
+OK …ready
USER mark
+OK please send PASS command
PASS abc?012
+OK 1 messages ready for mark in /usr/spool/mail/mark
LIST
+OK 1 messages; msg# and size for undeleted messages
1 461
.
RETR 1
+OK message 1
…. // The whole message content
.
DELE 1
+OK message 1 marked for deletion
LIST
+OK 1 messages; msg# and size for undeleted messages
.
QUIT
+OK … shutdown
Object Serialization
Moshe Fresko
Bar-Ilan University
Object Serialization

To represent an object in a byte-encoded
format that can be stored and passed to a
stream, and in need can be reconstructed.
Live Object
Live Object
Frozen Object Stream
Serialize
DeSerialize
Serialization

ObjectOutputStream & ObjectInputStream





Serialization can be used in.



Remote Method Invocation (RMI), communication between objects via
sockets. (Marshaling and unmarshaling objects)
Archival of an object for use in a later invocation of the same program.
Objects to be serialized



Works like other input-output streams
They can write and read Objects.
ObjectOutputStream: Serializes Java Objects into a byte-encoded
format, and writes them onto an OutputStream.
ObjectInputStream: Reads and reconstructs Java Objects from a byteencoded format read from InputStream.
Must implement Serializable interface
Non-persistent fields can be marked with transient keyword
The following is written and read during serialization



Class of the object
Class signature
Values of all non-transient and non-static members
Serialization

To Write into an ObjectOutputStream
FileOutputStream out = new FileOutputStream(“afile”) ;
ObjectOutputStream oos = new ObjectOutputStream(out) ;
oos.writeObject(“Today”) ;
oos.writeObject(new Date()) ;
oos.flush() ;

To Read from an ObjectInputStream
FileInputStream in = new FileInputStream(“afile”) ;
ObjectInputStream ois = new ObjectInputStream(in) ;
String today = (String) ois.readObject() ;
Date date = (Date) ois.readObject() ;
Serialization


ObjectOutputStream.writeObject(Object)
traverses all the internal references of the
object recursively and writes all of them.
ObjectOutputStream implements DataOutput
interface to write primitive data types.
writeInt(…), writeFloat(…), writeUTF(…), etc.

ObjectInputStream implements DataInput
interface ro read primitive data types.
readInt(), readFloat(), readUTF(), etc.

writeObject(Object) throws
NotSerializableException if Object does not
implement Serializable interface
Object Serialization Example
import java.io.* ;
import java.util.* ;
class A implements Serializable {
public int i = 5 ;
public String str = "Hi" ;
public List l = new ArrayList() ;
}
public class ObjSerTest {
public static void main(String[]args) {
A a = new A() ;
a.i = 10 ; a.str = "Hello" ;
a.l.add("One") ; a.l.add("Two") ;
serialize(a) ;
}
private static void serialize(A a) {
System.out.println("Serializing...");
try {
FileOutputStream fos = new FileOutputStream("test.out") ;
ObjectOutputStream oos = new ObjectOutputStream(fos) ;
oos.writeObject(a) ;
} catch (Exception e) {
System.err.println("Problem: "+e) ;
Object De-serialization Example
import java.io.* ;
import java.util.* ;
class A implements Serializable {
public int i = 5 ;
public String str = "Hi" ;
public List l = new ArrayList() ;
}
public class ObjDeSerTest {
public static void main(String[]args) {
A a = deserialize() ;
System.out.println(a.i) ;
System.out.println(a.str) ;
System.out.println(a.l) ;
}
private static A deserialize() {
System.out.println("DeSerializing...");
try {
FileInputStream fis = new FileInputStream("test.out") ;
ObjectInputStream iis = new ObjectInputStream(fis) ;
return (A) iis.readObject() ;
} catch (Exception e) {
System.err.println("Problem: "+e) ;
}
return null ;
}}
Customizing Serialization

To define writeObject() and readObject() to append
additional information.
private void writeObject(ObjectOutputStream oos) throws
IOException {
oos.defaultWriteObject() ;
// customized serialization code
}
private void readObject(ObjectInputStream ois) throws
IOException {
ois.defaultReadObject() ;
// customized deserialization code
// if necessary, must include code to update the object
}
Externalizable interface

To control the serialization process explicitly,
Externalizable interface must be implemented.

Externalizable interface
public interface Externalizable extends Serializable {
public void writeExternal(ObjectOutput out) throws
IOException ;
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException ;
}

writeExternal and readExternal must save/load the
state of the object. They must explicitly coordinate
with its supertype to save its state.
Java Applets
Moshe Fresko
Bar-Ilan University
Java Applets




Applet: A Java program that adheres to certain
conventions that allow it to be included in HTML
pages and executed within Java-enabled
browsers.
Compiled with regular JDK compiler (javac).
Can be checked by Applet Viewer program
(appletviewer) .
It can be included in an HTML to be run within a
browser.
Example Applet

HelloWorld.java
import java.applet.Applet ;
import java.awt.Graphics ;
public class HelloWorld extends Applet {
public void paint(Graphics g) {
g.drawString("Hello World!",50,25) ;
}
}

Hello.html
<HTML>
<HEAD><TITLE>A Simple Program</TITLE></HEAD>
<BODY>
Here is the output of the program:
<APPLET CODE="HelloWorld.class" WIDTH=150 HEIGHT=25></APPLET>
</BODY>
</HTML>


To Compile: javac HelloWorld.java
To run:


Either: To load Hello.html from a Java available browser
Or: To run: AppletViewer Hello.html
Applet class Hierarchy
java.lang.Object
java.awt.Component
java.awt.Container
java.applet.Applet
One Applet Class
javax.swing.JApplet
Another Applet Class
A Simple Applet
import java.applet.Applet ;
import java.awt.Graphics ;
public class Simple extends Applet {
StringBuffer buffer ;
public void init()
{ buffer = new StringBuffer() ;
addItem("initializing... ") ; }
public void start()
{ addItem("starting... ") ; }
public void stop()
{ addItem("stopping... ") ; }
public void destroy()
{ addItem("preparing for unloading... ") ; }
void addItem(String aWord)
{ System.out.println(aWord) ;
buffer.append(aWord) ;
repaint() ; }
public void paint(Graphics g)
{ g.drawRect(0,0,getSize().width-1,getSize().height-1) ;
g.drawString(buffer.toString(),5,15) ; }
}
Life Cycle of an Applet

Loading the Applet




Leaving and Returning to the Applet’s page.



When user leaves the page applet is stopped, and when the user
returns to the page it is restarted.
These processed are also done when the browser window is minimized
and restored.
Reloading the Applet




An instance of the applet’s subclass is created. (new MyApplet() )
The applet initializes itself (calls .init() method)
The applet starts running (calls .start() method)
Previous applet is stopped.
Some final clean-ups are done.
Then a new instance is loaded.
Quitting the Browser

Applet is stopped and some final clean-ups are done.
Applet Mile-Stone methods




init() : Automatically called to perform first-time
initialization of the applet.
start() : Called every time the applet moves into
sight on the Web browser to allow the applet to start
up its normal operations. Also called after init( ).
stop() : Called every time the applet moves out of
sight on the Web browser to allow the applet to shut
off expensive operations. Also called right before
destroy( ).
destroy() : Called when the applet is being
unloaded from the page to perform final release of
resources when the applet is no longer used
Methods for Drawing

Method for Drawing



Methods for Adding UI Components




paint(Graphics g) : Applets implement the paint method to
draw the applet’s representation within a browser window.
update(Graphics g) : A method that can be used with paint
to improve drawing performance.
add(…) : Adds the specified Component to the applet.
remove(…) : Removes the specified Component
setLayout(…) : Sets the applets layout manager
Methods for drawing and event handling

add???Listenet(???Listener) : Like in the regular Graphical
Components
Event Handling in Applets
import java.applet.Applet ;
import java.awt.Graphics ;
import java.awt.event.* ;
public class SimpleEvent extends Applet {
StringBuffer buffer ;
public void init()
{ buffer = new StringBuffer() ;
addMouseListener(new MyMouseListener()) ;
addItem("initializing... ") ; }
class MyMouseListener extends MouseAdapter
{ public void mouseClicked(MouseEvent event) { addItem("Click!...") ; } }
public void start() { addItem("starting... ") ; }
public void stop() { addItem("stopping... ") ; }
public void destroy() { addItem("preparing for unloading... ") ; }
void addItem(String aWord)
{ System.out.println(aWord) ;
buffer.append(aWord) ;
repaint() ; }
public void paint(Graphics g)
{ g.drawRect(0,0,getSize().width-1,getSize().height-1) ;
g.drawString(buffer.toString(),5,15) ; }
JApplet to GUI components


JApplet is the swing version of Applet.
The GUI component is added to the
internal container by using
getInternalPane() method.
JApplet example
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
// <applet code="ButtonsApplet.class" width=200 height=75></applet>
public class ButtonsApplet extends JApplet {
private JButton
b1 = new JButton("Button 1"),
b2 = new JButton("Button 2");
private JTextField txt = new JTextField(10);
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
String name = ((JButton)e.getSource()).getText();
txt.setText(name); }
}
private ButtonListener bl = new ButtonListener();
public void init() {
b1.addActionListener(bl); b2.addActionListener(bl);
Container cp = getContentPane();
cp.setLayout(new FlowLayout());
cp.add(b1); cp.add(b2); cp.add(txt);
}
}
Applet Restrictions


Arbitrary Applets loaded from the Net has maximal restrictions.
Browser can give to some Applets more access permissions.
Like:



Security Checking:


Applets with certain signatures
Applets loaded from a trusted url.
Each browser has a SecurityManager object that checks for applet
security violations on potentially troublesome operations. When a
SecurityManager detects a violation, it throws SecurityException.
Common Restrictions:





To load libraries or define native methods.
To read or write files on the host executing it.
To make network connections. (Except the host from which it
came)
To start another program on the host executing it
To get some system properties
Applet API








getCodeBase() : Returns the URL of the directory from which the applet’s
classes were loaded.
getDocumentBase() : Returns the URL of the directory of the HTML page
that contains the applet.
AppletContext getAppletContext()
AppletContext.showStatus(String) : Displays String in Status line.
AppletContext.showDocument(java.net.URL) :
AppletContext.showDocument(java.net.URL,String targetWindow) : Tells
browser to display the given URL’s content.
AppletContext.getApplet(String appletName) : Returns the Applet object
from the current page for the given name.
AppletContext.getApplets(String appletName) : Returns the Applets of the
page as an Enumeration of Applet objects.
Applet API – via AppletContext







showStatus(String) : Displays String in Status line.
showDocument(URL) :
showDocument(URL,String targetWindow) : Tells browser to
display the given URL’s content.
getApplet(String appletName) : Returns the Applet object from
the current page for the given name.
getApplets(String appletName) : Returns the Applets of the
page as an Enumeration of Applet objects.
AudioClip getAudioClip(URL)
AudioClip getAudioClip(URL,String)
Applet – Passing parameters


String getParameter(String name) : Returns the value
of the parameter as a string.
<APPLET CODE=“MyApplet.class” WIDTH=350
HEIGHT=60>
<PARAM NAME=“SOUND” VALUE=“music.au”>
<PARAM NAME=“IMAGES” VALUE=“i1.ico|i2.ico”>
<PARAM NAME=“TIMES” VALUE=10>
<PARAM NAME=“Name” VALUE=“MyApplet”>
<APPLET>