Unit-6
Applets:
Concepts of applets,
differences between applets and applications,
life cycle of an applet,
types of applets,
creating applets,
passing parameters to applets.
Networking:
Basics of network programming,
addresses, ports, sockets, simple client server program,
multiple clients, sending file from server to client.
1
Applets
2
What is an applet?
• a small Java program that can be inserted into a web page and
run by loading that page in a browser.
• An applet, like any application program, can do many things.
• It can perform arithmetic operations, display graphics, play
sounds, accept user input, create animation, and so on.
• This is the feature of Java that is primarily responsible for its
initial popularity.
• Users can run applets simply by visiting a web page that
contains an applet program.
3
Applet execution by a browser
4
Applet classes in Java
• Implementation
– a top-level container, like a Frame.
– behaves more like a Panel.
– It does not contain a title bar, menu bar, or border.
– This is why you don’t see these items when an applet is run
inside a browser.
– When you run an applet using an applet viewer, the applet
viewer provides the title and border.
– [Link]
5
How Applets Differ from Applications
• Although both the Applets and stand-alone
applications are Java programs, there are certain
restrictions are imposed on Applets due to security
concerns:
– Applets don’t use the main() method, but when they are loaded,
automatically call certain methods (init, start, paint, stop,
destroy).
– They are embedded inside a web page and executed in browsers.
– Takes input through Graphical User Interface(GUI).
– They cannot read from or write to the files on local computer.
– They cannot run any programs from the local computer.
– They are restricted from using libraries from other languages.
• The above restrictions ensures that an Applet cannot
do any damage to the local system.
6
Building Applet Code: An Example
import [Link].*;
import [Link];
public class SimpleApplet extends Applet {
public void paint(Graphics g) {
[Link] ("A Simple Applet",20, 20);
}
}
Begins with two import classes.
[Link].* -- required for GUI
[Link].* -- every applet you create must be a subclass
of Applet, which is in [Link] package.
The class should start with public, because it is accessed
from outside.
7
• Applets do not begin execution at main().
• An applet begins its execution when the name of its
class is passed to an applet viewer or to a network
browser.
• Compile the applet in the same way that we have
been compiling programs.
• Running an applet involves a different process.
8
Running an Applet
1. Using web browser
2. Using appletviewer
9
Executing in a web browser.
• To execute an applet in a web browser, you need to write a
short HTML file that contains a tag (Applet) that loads the
applet.
HTML file that contains a SimpleApplet
<APPLET code="SimpleApplet"
width=400 height=300> </APPLET>
• Save this file with .html extension
• After you create this file, open your browser and then load this
file, which causes SimpleApplet to be executed.
• Width and height specify the dimensions of the display used
by the applet. 10
Output:
11
Executing by using appletviewer
– appletviewer. An applet viewer executes your
applet in a window.
– This is generally the fastest and easiest way to test
your applet.
12
• There are two ways
1. Use earlier html page, which contains applet tag,
then execute by using following command.
• C:\>appletviewer [Link]
13
Output:
14
2. Include a comment at the beginning of your
source code file that contains the applet tag, then
start applet viewer with your java source code file.
• C:\>appletviewer [Link]
15
Ex:-
import [Link].*;
import [Link];
/* <applet code="SimpleApplet" width=400
height=300 ></applet> */
public class SimpleApplet extends Applet {
public void paint(Graphics g) {
[Link] ("A Simple Applet",20, 20);
}
}
Compile and then execute by using following
command
C:\>appletviewer [Link] 16
Output:
17
Structure of an applet
import [Link].*;
import [Link].*;
/*
<applet code="AppletStructure" width=300 height=100>
</applet>
*/
public class AppletStructure extends Applet {
// Called first.
public void init() {
// initialization
}
/* Called second, after init(). Also called whenever
the applet is restarted. */
public void start() {
// start or resume execution 18
}
// Called when the applet is stopped.
public void stop() {
// suspends execution
}
/* Called when applet is terminated. This is the last
method to be executed. */
public void destroy() {
// perform shutdown activities
}
// Called whenever an applet's output must be redisplayed.
public void paint(Graphics g) {
// redisplay contents of window
}
}
19
Life cycle of an Applet
init()
Begin Born
stop()
start()
Running Idle
destroy()
paint() start()
Dead End
Fig: Applet Life Cycle Diagram
20
• When an applet is started , the following sequence of
method calls takes place:
1. init( )
2. start( )
3. paint( )
• When an applet is terminated, the following sequence
of method calls takes place:
1. stop( )
2. destroy( )
21
Applet States
init()- called only once
– The init( ) method is the first method to be called.
– This is where you should initialize variables.
– This method is called only once during the run time of
your applet.
start()- called more than once
– The start( ) method is called after init( ).
– start( ) is called each time an applet’s HTML document is
displayed on screen.
– So, if a user leaves a web page and comes back, the applet
resumes execution at start( ).
22
paint( )- called more than once
• The paint( ) method is called each time your applet’s output
must be redrawn.
• For example, when the applet window is minimized and then
restored.
• paint( ) is also called when the applet begins execution.
• The paint( ) method has one parameter of type Graphics. This
parameter is used to draw graphics.
23
stop( ) - called more than once
• The stop( ) method is called when a web browser leaves the
HTML document containing the applet.
• for example when it goes to another page.
• When stop( ) is called, the applet is probably running.
• You should use stop( ) to suspend threads that don’t need to
run when the applet is not visible.
• You can restart them when start( ) is called if the user returns
to the page.
24
destroy( ) - called only once
• The destroy( ) method is called whenever the browser is
closed.
• Applet is removed completely from memory.
• At this point, you should free up any resources the applet may
be using.
• The stop( ) method is always called before destroy( ).
25
Creating Applets
/* A simple applet that sets the foreground and
background colors and outputs a string. */
import [Link].*;
import [Link].*;
/*
<applet code="Sample" width=300 height=50>
</applet>
*/
public class Sample extends Applet{
String msg;
// set the foreground and background colors.
public void init() {
setBackground([Link]);
setForeground([Link]);
msg = "Inside init( ) --";
}
// Initialize the string to be displayed.
public void start() {
msg += " Inside start( ) --"; 26
}
// Display msg in applet window.
public void paint(Graphics g) {
msg += " Inside paint( ).";
[Link](msg, 10, 30);
}
public void stop()
{
[Link]("Inside stop( )");
}
public void destroy()
{
[Link]("Inside destroy( )");
} Output:
}
27
After closing appletviewer stop( ) and destroy( ) methods will be called.
Output in the command prompt:
Inside stop( )
Inside destroy( )
Passing Parameters to Applet
• The PARAM tag in HTML allows you to pass
parameters to your applet.
• To retrieve a parameter, use the getParameter( )
method.
• It returns the value of the specified parameter in the
form of a String object.
28
Applet Program Accepting Parameters
//[Link]
import [Link];
import [Link].*;
/* <APPLET
CODE="HelloAppletMsg" width=200 height=200>
<PARAM NAME="Greetings" VALUE="Hello World!">
</APPLET> */
public class HelloAppletMsg extends Applet {
String msg;
This is name of parameter specified in PARAM tag;
This method returns the value of paramter.
public void init()
{
msg = getParameter("Greetings");
if( msg == null)
msg = "Hello";
29
}
public void paint(Graphics g) {
[Link] (msg,50, 100);
}
}
Output:
30
Types of applets
• There are two types of applets.
– First is based on the Applet class
• These applets use the AWT classes to provide the GUI.
• This style of applet has been available since java was
created.
• It is used for simple GUI’s.
– The second is based on the Swing class JApplet.
• These applets use the Swing classes to provide the GUI.
• Swing offers a richer and easy to use interface than
AWT .
• Swing based applets are more popular.
31
Basics of network programming
IP Address
• 32-bit identifier
• Dotted-quad: [Link]
• Identifies a host
[Link]
32
Ports
Identifying the specific application
• IP addresses identify hosts
• Host has many applications
• Ports (16-bit identifier)
Application WWW E-mail Telnet
Port 80 25 23
[Link] 33
Sockets
• Socket is an object used for network programming.
• A socket is bound to a specific port number
• Network communication using Sockets is very much similar to
performing file I/O
34
Socket Communication
• A server (program) runs on a specific
computer and has a socket that is bound to a
specific port. The server waits and listens to
the socket for a client to make a connection
request.
Connection request
port
Server
Client
35
• If everything goes well, the server accepts the connection.
Upon acceptance, the server gets a new socket bounds to a
different port. It needs a new socket (consequently a different
port number) so that it can continue to listen to the original
socket for connection requests while serving the connected
client. port
server
port
Client
port Connection
36
Client-Server communication
Server
socket()
bind()
Client
listen()
socket()
accept()
connect()
block
write()
read()
process
request
write()
read() 37
Java’s .net package
Java’s .net package provides two classes:
– Socket – for implementing a client
– ServerSocket – for implementing a server
38
Implementing a Server
1. Open the Server Socket:
ServerSocket server = new ServerSocket( PORT );
2. Wait for the Client Request:
Socket s = [Link]();
3. Create I/O streams for communicating to the client
DataInputStream dis = new DataInputStream( [Link]() );
DataOutputStream dos = new DataOutputStream( [Link]() );
4. Perform communication with client
Receive data from client: String line = [Link]();
Send data to the client: [Link] ("Hello\n");
5. Close sockets: [Link]();
39
Implementing a Client
1. Create a Socket Object:
Socket client = new Socket( server, port_id );
2. Create I/O streams for communicating with the server.
DataInputStream dis = new DataInputStream([Link]() );
DataOutputStream dos = new DataOutputStream( [Link]() );
3. Perform communication with the server:
– Receive data from the server:
String line = [Link]();
– Send data to the server:
[Link] ("Hello\n");
4. Close the socket when done:
[Link]();
40
Simple client-serever program
A simple server (simplified code)
// [Link]: a simple server program
import [Link].*;
import [Link].*;
public class SimpleServer
{
public static void main(String args[]) throws IOException
{
// Register service on port 1234
ServerSocket server = new ServerSocket(1234);
Socket s=[Link](); // Wait and accept a connection
[Link]("Connection Established");
// Get a communication stream associated with the socket
DataOutputStream dos = new DataOutputStream([Link]());
// Send a string!
[Link]("Hello Client");
// Close the connection, but not the server socket
[Link]();
[Link]();
} 41
}
A simple client (simplified code)
// [Link]: a simple client program
import [Link].*;
import [Link].*;
public class SimpleClient
{
public static void main(String args[]) throws IOException
{ server_IP
// Open your connection to a server, at port 1234
Socket client = new Socket("localhost",1234);
// Get an input file handle from the socket and read the input
DataInputStream dis = new DataInputStream([Link]());
String str = [Link]();
[Link](str);
// When done, just close the connection and exit
[Link]();
[Link]();
}
} 42
Server side
Client side
43
Serving Multiple Clients
Multiple clients are quite often connected to a single server at the same time.
Typically, a server runs constantly on a server computer, and clients from all over
the Internet may want to connect to it. You can use threads to handle the server's
multiple clients simultaneously. Simply create a thread for each connection. Here is
how the server handles the establishment of a connection:
while (true) {
Socket socket = [Link]();
Thread thread = new Thread(new ThreadClass(socket));
[Link]();
}
The server socket can have many connections. Each iteration of the while loop
creates a new connection. Whenever a connection is established, a new thread is
created to handle communication between the server and the new client; and this
allows multiple connections to run at the same time.
44
Example: Serving Multiple
Clients
Server
A serve socket
on a port
Server for Multiple Clients A socket for a A socket for a
client client
Start Server
Client 1 ... Client n
Start Client
Note: Start the server first, then start multiple clients.
45
Sending file from server to client
Server program
import [Link].*;
import [Link].*;
class FTServer{
public static void main(String args[])throws Exception{
ServerSocket ss=new ServerSocket(2424);
Socket s=[Link]();
[Link]("Connection Established\n");
File myFile = new File (“E:/Programs/[Link]");
FileInputStream fis = new FileInputStream(myFile);
DataInputStream dis=new DataInputStream(fis);
byte [] mybytearray = new byte [(int)[Link]()];
[Link](mybytearray,0,[Link]);
DataOutputStream dos=new DataOutputStream([Link]());
[Link](mybytearray,0,[Link]);
[Link]("File has been sent successfully...");
[Link]();
[Link]();
[Link]();
[Link]();
} 46
}
Client program
import [Link].*;
import [Link].*;
class FRClient{
public static void main(String args[])throws Exception{
Socket s=new Socket("localhost",2424);
[Link]("waiting for File from Server.....");
DataInputStream dis=new DataInputStream([Link]());
String str;
boolean b=true;
while(b){
str=[Link]();
if(str==null)
b=false;
else
[Link](str);
}
[Link]();
[Link]();
}
} 47
48