Download APPLET

Document related concepts
no text concepts found
Transcript
Network Programming With
Java
Hilal Arslan
Hale Müge Kıncak
What is Next?
 Applets
 URL Objects
 Datagram Objects
What is an Applet
An applet is a program written in the JavaTM programming
language that can be included in an HTML page, much in
the same way an image is included. When you use a Java
technology-enabled browser to view a page that contains an
applet, the applet's code is transferred to your system and
executed by the browser's Java Virtual Machine (JVM).
Compiling an Applet
C:\>javac Applet1.java
C:\>appletviewer Applet1.html
The Applet class must be the superclass of any applet that is
to be embedded in a Web page or viewed by the Java Applet
Viewer. The Applet class provides a standard interface
between applets and their environment.
Inheritance Hierarchy of the Applet Class
Every applet is implemented by creating a subclass of the
Applet class.
The Life Cycle of an Applet
 Loading The Applet
– An instance of the applet's controlling class (an Applet subclass)
is created.
– The applet initializes itself.
– The applet starts running
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 newWord) {
System.out.println(newWord);
buffer.append(newWord);
repaint();
}
public void paint(Graphics g) {
//Draw a Rectangle around the applet's display area.
g.drawRect(0, 0, size().width - 1, size().height - 1);
//Draw the current string inside the rectangle.
g.drawString(buffer.toString(), 5, 15);
}
Leaving and Returning to the Applet's Page
When the user leaves the page -- for example, to go to
another page -- the applet has the option of stopping
itself. When the user returns to the page, the applet can
start itself again. The same sequence occurs when the
user iconifies and then reopens the window that
contains the applet. (Other terms used instead of
iconify are minaturize, minimize, and close.)
Reloading the Applet
Some browsers let the user reload applets, which
consists of unloading the applet and then loading it
again. Before an applet is unloaded, it's given the
chance to stop itself and then to perform a final
cleanup, so that the applet can release any
resources it holds
Quitting the Browser
When the user quits the browser (or whatever
application is displaying the applet), the applet has the
chance to stop itself and do final cleanup before the
browser exits.
Summary
An applet can react to major events in the following ways:
It can initialize itself.
It can start running.
It can stop running.
It can perform a final cleanup, in preparation
for being unloaded.
Methods for Milestones
public class Simple extends Applet {
. . .
public void init() { . . . }
public void start() { . . . }
public void stop() { . . . }
public void destroy() { . . . }
. . .
}
Adding UI Components
Pre-Made UI Components
The AWT supplies the following UI components (the class that implements
each component is listed in parentheses):
Buttons (java.awt.Button)
Checkboxes (java.awt.Checkbox)
Single-line text fields (java.awt.TextField)
Larger text display and editing areas (java.awt.TextArea)
Methods for Using UI Components in Applets
add
Adds the specified Component.
remove
Removes the specified Component.
setLayout
Sets the layout manager.
Security Restrictions
 Applets cannot load libraries or define native methods.
 An applet cannot ordinarily read or write files on the
host that is executing it.
 An applet cannot make network connections except to
the host that it came from.
 An applet cannot start any program on the host that is
executing it.
 An applet cannot read certain system properties.
 Windows that an applet brings up look different than
windows that an application brings up.
Windows that an applet brings up look different
than windows that an application brings up.
Applet Capabilities
Here are some other things that current browers and other applet viewers let
applets do:
Applets can usually make network connections to the host they came from.
Applets running within a Web browser can easily cause HTML documents
to be displayed.
Applets can invoke public methods of other applets on the same page.
Applets that are loaded from the local file system (from a directory in the
user's CLASSPATH) have none of the restrictions that applets loaded over
the network do.
Although most applets stop running once you leave their page, they don't
have to.
Using the APPLET Tag
Here's the simplest form of the
<APPLET> tag:
<APPLET CODE=AppletSubclass.class
WIDTH=anInt HEIGHT=anInt>
</APPLET>
When a Java-enabled browser encounters an <APPLET> tag,
it reserves a display area of the specified width and height for
the applet, loads the bytecodes for the specified Applet
subclass, creates an instance of the subclass, and then calls
the instance's init and start methods.
Specifying Parameters
Some applets let the user customize the
applet's configuration with parameters.
<APPLET CODE="Animator.class" WIDTH=460
HEIGHT=160>
<PARAM NAME="imageSource" VALUE="images/Beans">
<PARAM NAME="backgroundColor" VALUE="0xc0c0c0">
<PARAM NAME="endImage" VALUE=10>
<PARAM NAME="soundSource" VALUE="audio">
<PARAM NAME="soundtrack" VALUE="spacemusic.au">
<<PARAM NAME="pause" VALUE=200>
. . .
</APPLET>
Specifying Alternate HTML Code and
Text
HTML code interpreted only by browsers that don't understand the
<APPLET> tag. Alternate HTML code is any text that appears between
the <APPLET> and </APPLET> tags, after any <PARAM> tags. Javaenabled browsers ignore alternate HTML code.
<APPLET CODE="Animator.class" WIDTH=460 HEIGHT=160
ALT="If you could run this applet, you'd see some
animation">
<PARAM NAME="imageSource" VALUE="images/Beans">
<PARAM NAME="backgroundColor" VALUE="0xc0c0c0">
<PARAM NAME="endImage" VALUE=10>
<PARAM NAME="soundSource" VALUE="audio">
<PARAM NAME="soundtrack" VALUE="spacemusic.au">
Your browser is completely ignoring the &lt;APPLET&gt;
tag!
</APPLET>
Specifying the Applet Directory
<APPLET CODE=Simple.class CODEBASE="example/"
WIDTH=500 HEIGHT=20>
</APPLET>
By default, a browser looks for an
applet's class and archive files in the
same directory as the HTML file that
has the <APPLET> tag. Sometimes,
however, it's useful to put the applet's
files somewhere else. You can use the
CODEBASE attribute to tell the browser
in which directory the applet's files are
located:
Finding and Loading Data Files
 Applet getCodeBase method:, is a URL that specifies
the directory from which the applet's classes were loaded.
 Applet getDocumentBase method: specifies the
directory of the HTML page that contains the applet.
Image image = getImage(getCodeBase(), "imgDir/a.gif");
Unless the <APPLET> tag specifies a code base, both the code base
and document base refer to the same directory on the same server.
HelloWorld.class c:\deneme
HelloWorld.html c:\java
<HTML>
<HEAD>
<TITLE>A Simple Program</TITLE>
</HEAD>
<BODY>
Here is the output of my program:
<APPLET CODE=HelloWorld.class CODEBASE="http://Hilal1/deneme/"
WIDTH=150 HEIGHT=25>
</APPLET>
</BODY>
</HTML>
Displaying Short Status Strings and
Documents in an Applet
Applets display status lines with the showStatus method.
Here's an example of its use:
showStatus("MyApplet: Loading image file " + file);
Have you ever wanted an applet to display formatted HTML
text? Here's the easy way to do it:
public void showDocument(java.net.URL url)
public void showDocument(java.net.URL url, String
targetWindow)
Sending Messages to Other Applets
AppletContext getApplet() method. (by name)
AppletContext getApplets() method
Both methods, if successful, give the caller one or more
Applet objects. Once the caller finds an Applet object, the
caller can invoke methods on the object.
Finding an Applet by Name: The getApplet
Method
By default, an applet has no name. For an applet to have a name,
one must be specified in the HTML code that adds the applet to a
page. You can specify an applet's name in two ways:
•By specifying a NAME attribute within the applet's <APPLET>
tag. For example:
<APPLET CODEBASE=example/ CODE=Sender.class
WIDTH=450 HEIGHT=200 NAME="buddy">. . .</applet>
•By specifying a NAME parameter with a <PARAM> tag. For
example:
<APPLET CODEBASE=example/ CODE=Receiver.class
WIDTH=450
HEIGHT=35>
<PARAM NAME="name" value="old pal">
. . .</applet>
Getting SystemProperties
Key
Meaning
"java.vendor"
Java vendor-specific string
"java.version"
Java version number
"os.arch"
Operating system architecture
"os.name"
Operating system name
"path.separator"
Path separator (for example, ":")
To read a system property from within an applet, the applet uses the System
class method getProperty. For example:
String newline = System.getProperty("os.name");
Threads in Applets
A thread is a single sequential flow of control within a program.
However, a thread itself is not a program; it cannot run on its
own. Rather, it runs within a program.
Some texts use the name lightweight process instead of thread
Multiple threads in a single program, running at the same time
and performing different tasks.
Multiple Threds
Every applet can run in multiple threads.
Many browsers allocate a thread for each applet on a page,
using that thread for all calls to the applet's major
milestone methods. Some browsers allocate a thread group
for each applet, so that it's easy to kill all the threads that
belong to a particular applet
Why Would an Applet Need To Create and
Use Its Own Threads?
Time Conservation: If an applet performs a time-consuming
task, it should create and use its own thread to perform that
task.
•Using Threads For Repeatative Tasks
•Using Threads For One Time Initialization
Server Application That Executes on the
Applet's Host.
This page features an example of a server that allows two applets to
communicate with each other. The applets don't have to be running on the
same page, in the same browser, or on the same computer. As long as the
applets originate from the same computer, they can communicate through
the server that's running on that originating computer. Here are the source
files:
TalkServer.java
TalkClientApplet.java
TalkServerThread.java
www% java TalkServer
TalkServer listening on rendezvous port:
36567
Network Programming with Java
1) URL
2)Datagrams
What Is a URL?
URL(Uniform Resource Locator) is a
reference (an address) to a resource on
the Internet.
 "URL address” ==> an Internet address
 "URL object” ==> an instance of the URL
class in a program.
Creating a URL
 URL gamelan = new URL("http://www.gamelan.com/");
 URL(URL baseURL, String relativeURL)
URL gamelanGames =
new URL(gamelan, "Gamelan.net.html");
 new URL("http", "www.gamelan.com", 80,
"pages/Gamelan.network.html");
creates a URL object for the following URL:
http://www.gamelan.com:80/pages/Gamelan.network.htm
!
URLs are "write-once" objects. Once
you've created a URL object, you cannot
change any of its attributes (protocol,
host name, filename, or port number).
Parsing a URL
import java.net.*;
import java.io.*;
public class ParseURL {
public static void main(String[] args) throws Exception {
URL aURL = new
URL("http://java.sun.com:80/docs/books/tutorial/intro.html#DOWNLOADING");
System.out.println("protocol = " + aURL.getProtocol());
System.out.println("host = " + aURL.getHost());
System.out.println("filename = " + aURL.getFile());
System.out.println("port = " + aURL.getPort());
System.out.println("ref = " + aURL.getRef());
}
}
protocol = http
host = java.sun.com
filename = /docs/books/tutorial/intro.html
port = 80
ref = DOWNLOADING
Reading Directly from a URL
You can call the URL's openStream()
method to get a stream from which you
can read the contents of the URL.
The openStream() method returns a
java.io.InputStream object.
openStream()
import java.net.*;
import java.io.*;
public class URLReader {
public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.yahoo.com/");
BufferedReader in =
new BufferedReader( new InputStreamReader( yahoo.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
The output: either the HTML commands and textual content
or the program might hang or you might see an exception
stack trace.
Connecting to a URL
 URL object's openConnection method is used to connect to
a URL.
 Connecting to a URL means initializing a communication
link between the Java program and the URL over the
network.
try {
URL yahoo = new URL("http://www.yahoo.com/");
yahoo.openConnection();
} catch (MalformedURLException e) {
// new URL() failed . . .
}
catch (IOException e) {
// openConnection() failed . . .
}
Reading from a URLConnection
import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL yahoo = new URL("http://www.yahoo.com/");
URLConnection yc = yahoo.openConnection();
BufferedReader in = new BufferedReader( new
InputStreamReader( yc.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
}
The output from this program is identical to the output
from the program that opens a stream directly from the
URL.
Writing to a URLConnection
 Create a URL.
 Open a connection to the URL.
 Set output capability on the URLConnection.
 Get an output stream from the connection. This
output stream is connected to the standard input
stream of the cgi-bin script on the server.
 Write to the output stream.
 Close the output stream.
An example program that runs the backwards
script over the network through a
URLConnection:
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_to_reverse");
System.exit(1);
}
String stringToReverse = URLEncoder.encode(args[0]);
URL url = new URL("http://java.sun.com/cgi-bin/backwards");
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(connection.getOutputStream());
out.println("string=" + stringToReverse);
out.close();
BufferedReader in = new BufferedReader( new InputStreamReader(
connection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine);
in.close();
}
What Is a Datagram?
A datagram is an independent, selfcontained message sent over the network
whose arrival, arrival time, and content
are not guaranteed.
URL, SOCKET vs. DATAGRAM
URL or SOCKET
 Connection-based
 Reliable
 Dedicated pointto-point channel
 Same order
DATAGRAMS
 Not connection-based
 No guarantees about arriva
 Don’t have a dedicated
point-to-point channel
 The order is not
guaranteed
TCP vs. UDP
TCP: a server application
binds a socket to a specific
port number. This has the
effect of registering the
server with the system to
receive all data destined for
that port..
UDP: the datagram packet
contains the port number of
its destination and UDP
routes the packet to the
appropriate application.
3 important classes
 DatagramSocket
Represents a socket for sending and receiving datagram
packets.
 DatagramPacket
Represents a datagram packet used to implement a
connectionless packet delivery service.
 MulticastSocket
It is a DatagramSocket, with additional capabilities for
joining "groups" of other multicast hosts on the internet.
It is useful for sending and receiving IP multicast packets.
Sample Datagram Client
and Server
 The server continuously receives datagram
packets over a datagram socket. Each
datagram packet received by the server
indicates a client request for a quotation.
When the server receives a datagram, it
replies by sending a datagram packet that
contains a one-line "quote of the moment"
back to the client.
 The client application in this example is
fairly simple. It sends a single datagram
packet to the server indicating that the client
would like to receive a quote of the
moment. The client then waits for the server
to send a datagram packet in response.
Server Application
Two classes implement the server application: QuoteServer
and QuoteServerThread
 The QuoteServer
import java.io.*;
public class QuoteServer {
public static void main(String[] args) throws IOException {
new QuoteServerThread().start();
}
}
QuoteServerThread
import java.io.*;
import java.net.*;
import java.util.*;
public class QuoteServerThread extends Thread {
protected DatagramSocket socket = null;
protected BufferedReader in = null;
protected boolean moreQuotes = true;
public QuoteServerThread() throws IOException {
this("QuoteServerThread");
}
public QuoteServerThread(String name) throws IOException {
super(name);
socket = new DatagramSocket(4445);
try {
in = new BufferedReader(new FileReader("one-liners.txt"));
} catch (FileNotFoundException e) {
System.err.println("Could not open quote file. Serving time instead.");
}
}
Run Method
public void run() {
while (moreQuotes) {
try {
byte[] buf = new byte[256];
// receive request
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
// figure out response
String dString = null;
if (in == null)
dString = new Date().toString();
else
dString = getNextQuote();
buf = dString.getBytes();
// send the response to the client at "address" and "port"
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();
}
GetNextQuote
protected String getNextQuote() {
String returnValue = null;
try {
if ((returnValue = in.readLine()) == null) {
in.close();
moreQuotes = false;
returnValue = "No more quotes. Goodbye.";
}
} catch (IOException e) {
returnValue = "IOException occurred in server.";
}
return returnValue;
}
}
Client Application
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.out.println("Usage: java QuoteClient ");
return;
}
// get a datagram socket
DatagramSocket socket = new DatagramSocket();
// send request
byte[] buf = new byte[256];
InetAddress address = InetAddress.getByName(args[0]);
DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445);
socket.send(packet);
// get response
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
// display response
String received = new String(packet.getData());
System.out.println("Quote of the Moment: " + received);
socket.close();
}
}
Broadcasting to Multiple Recipients
 MulticastSocket is used on the client-side to listen
for packets that the server broadcasts to multiple
clients.
 The QuoteServer
import java.io.*;
public class MulticastServer {
public static void main(String[] args) throws IOException {
new MulticastServerThread ().start();
}
}
QuoteServerThread
public class MulticastServerThread extends QuoteServerThread {
…
}
 Run Method
public void run() {
while (moreQuotes) {
try {
byte[] buf new byte[256];
// don't wait for request...just send a quote
String dString = null;
if (in == null)
dString = new Date().toString();
else
dString = getNextQuote();
buf = dString.getBytes();
InetAddress group = InetAddress.getByName("230.0.0.1");
DatagramPacket packet;
packet = new DatagramPacket(buf, buf.length, group, 4446);
socket.send(packet);
try {
sleep((long)Math.random() * FIVE_SECONDS);
} catch (InterruptedException e) { }
} catch (IOException e) {
e.printStackTrace();
moreQuotes = false;
}
}
socket.close();
}
Client Application
MulticastSocket socket = new MulticastSocket(4446);
InetAddress group = InetAddress.getByName("230.0.0.1");
socket.joinGroup(group);
DatagramPacket packet;
for (int i = 0; i < 5; i++) {
byte[] buf = new byte[256];
packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String received = new String(packet.getData());
System.out.println("Quote of the Moment: " + received);
}
socket.leaveGroup(group);
socket.close();
Thanks!
Any Questions?