0% found this document useful (0 votes)
6 views16 pages

Advance Java Bvoc3_u1 - Copy

The document provides an overview of Java Networking and Java Applets, explaining the concepts of connecting devices to share resources and the role of applets in web pages. It details the differences between Java applications and applets, the use of DatagramSocket and DatagramPacket classes for network communication, and the applet life cycle with its core methods. Additionally, it distinguishes between local and remote applets, highlighting their characteristics and usage in web development.

Uploaded by

dabsaraheet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views16 pages

Advance Java Bvoc3_u1 - Copy

The document provides an overview of Java Networking and Java Applets, explaining the concepts of connecting devices to share resources and the role of applets in web pages. It details the differences between Java applications and applets, the use of DatagramSocket and DatagramPacket classes for network communication, and the applet life cycle with its core methods. Additionally, it distinguishes between local and remote applets, highlighting their characteristics and usage in web development.

Uploaded by

dabsaraheet
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Unit – 1

Java Networking & Java Applet


 Java Networking

Java networking is the concept of connecting two or more computing devices to share resources. The
application layer of a Java program communicates with the network. The java.net package contains all of the
Java networking classes and interfaces.

Java networking is the concept of using Java programming language to create applications that can
communicate over a network. A network is a collection of devices that are connected by some medium, such
as wires, cables, or wireless signals, and can exchange data with each other.

 Java Applet

A Java application that is integrated into a webpage is called an applet. It functions as a front-end and is run
within the web computer. It makes a page more interactive and dynamic by operating inside the web
browser. Applets are hosted on web servers and inserted into HTML pages via the OBJECT or APPLET tags.

 What is the difference between Java application and applet?


Java applications are programs that run on a system without any web browser. Java Applets are the programs
that need a Java-supported web browser for their execution.

 Socket
 Datagram

Datagrams are collection of information sent from one device to another device via the established network.
When the datagram is sent to the targeted device, there is no assurance that it will reach to the target device
safely and completely. It may get damaged or lost in between. Likewise, the receiving device also never know
if the datagram received is damaged or not. The UDP protocol is used to implement the datagrams in Java.

 Java DatagramSocket class

Java DatagramSocket class represents a connection-less socket for sending and receiving datagram packets. It
is a mechanism used for transmitting datagram packets over network.`

A datagram is basically an information but there is no guarantee of its content, arrival or arrival time.
Commonly used Constructors of DatagramSocket class

o DatagramSocket() throws SocketEeption: it creates a datagram socket and binds it with the available
Port Number on the localhost machine.
o DatagramSocket(int port) throws SocketEeption: it creates a datagram socket and binds it with the
given Port Number.
o DatagramSocket(int port, InetAddress address) throws SocketEeption: it creates a datagram socket
and binds it with the specified port number and host address.

Java DatagramSocket Class

Method Description

void bind(SocketAddress addr) It binds the DatagramSocket to a specific address and port.

void close() It closes the datagram socket.

void connect(InetAddress address, It connects the socket to a remote address for the socket.
int port)

void disconnect() It disconnects the socket.

boolean getBroadcast() It tests if SO_BROADCAST is enabled.

DatagramChannel getChannel() It returns the unique DatagramChannel object associated


with the datagram socket.

InetAddress getInetAddress() It returns the address to where the socket is connected.

InetAddress getLocalAddress() It gets the local address to which the socket is connected.

int getLocalPort() It returns the port number on the local host to which the
socket is bound.

SocketAddress It returns the address of the endpoint the socket is bound


getLocalSocketAddress() to.

int getPort() It returns the port number to which the socket is connected.

int getReceiverBufferSize() It gets the value of the SO_RCVBUF option for this
DatagramSocket that is the buffer size used by the platform
for input on the DatagramSocket.

boolean isClosed() It returns the status of socket i.e. closed or not.

boolean isConnected() It returns the connection state of the socket.

void send(DatagramPacket p) It sends the datagram packet from the socket.

void receive(DatagramPacket p) It receives the datagram packet from the socket.


 Java DatagramPacket Class

Java DatagramPacket is a message that can be sent or received. It is a data container. If you send multiple
packet, it may arrive in any order. Additionally, packet delivery is not guaranteed.

Commonly used Constructors of DatagramPacket class

o DatagramPacket(byte[] barr, int length): it creates a datagram packet. This constructor is used to
receive the packets.
o DatagramPacket(byte[] barr, int length, InetAddress address, int port): it creates a datagram packet.
This constructor is used to send the packets.

Java DatagramPacket Class Methods

Method Description

1) InetAddress getAddress() It returns the IP address of the machine to which the


datagram is being sent or from which the datagram was
received.

2) byte[] getData() It returns the data buffer.

3) int getLength() It returns the length of the data to be sent or the length
of the data received.

4) int getOffset() It returns the offset of the data to be sent or the offset
of the data received.

5) int getPort() It returns the port number on the remote host to which
the datagram is being sent or from which the datagram
was received.

6) SocketAddress getSocketAddress() It gets the SocketAddress (IP address + port number) of


the remote host that the packet is being sent to or is
coming from.

7) void setAddress(InetAddress iaddr) It sets the IP address of the machine to which the
datagram is being sent.

8) void setData(byte[] buff) It sets the data buffer for the packet.

9) void setLength(int length) It sets the length of the packet.

10) void setPort(int iport) It sets the port number on the remote host to which
the datagram is being sent.

11) void setSocketAddress(SocketAddress It sets the SocketAddress (IP address + port number) of
addr) the remote host to which the datagram is being sent.
 URL
URL represents a Uniform Resource Locator. Create an Java object that represents an URL using the
constructor of the URL class. URL url = new URL(“http://www.cs.ust.hk/~lzhang/comp201/index.html”); The
instance methods of the URL class are etc.
 URLConnection is an abstract class. The two subclasses HttpURLConnection and JarURLConnection
makes the connetion between the client Java program and URL resource on the internet. With the
help of URLConnection class, a user can read and write to and from any resource referenced by an URL
object.

Applet Programming :

 Types of Applets in Java

A special type of Java program that runs in a Web browser is referred to as Applet. It has less response time
because it works on the client-side. It is much secured executed by the browser under any of the platforms
such as Windows, Linux and Mac OS etc. There are two types of applets that a web page can contain.

1. Local Applet
2. Remote Applet

Let's understand both types of Applet one by one:

Local Applet

Local Applet is written on our own, and then we will embed it into web pages. Local Applet is developed
locally and stored in the local system. A web page doesn't need the get the information from the internet
when it finds the local Applet in the system. It is specified or defined by the file name or pathname. There are
two attributes used in defining an applet, i.e., the codebase that specifies the path name and code that
defined the name of the file that contains Applet's code.

Specifying Local applet


1. <applet
2. codebase = "tictactoe"
3. code = "FaceApplet.class"
4. width = 120
5. height = 120>
6. </applet>

Let's take an example of Local applet to understand how we can create it and embedded it into web page.

1. First, we will create a Local Applet for embedding in a web page.


2. After that, we will add that Local Applet to the web page.

FaceApplet.java

1. //Import packages and classes


2. import java.applet.*;
3. import java.awt.*;
4. import java.util.*;
5. import java.awt.event.*;
6. //Creating FaceApplet class that extends Applet
7. public class FaceApplet extends Applet
8. {
9. //paint() method starts
10. public void paint(Graphics g){
11. //Creating graphical object
12. g.setColor(Color.red);
13. g.drawString("Welcome", 50, 50);
14. g.drawLine(20, 30, 20, 300);
15. g.drawRect(70, 100, 30, 30);
16. g.fillRect(170, 100, 30, 30);
17. g.drawOval(70, 200, 30, 30);
18. g.setColor(Color.pink);
19. g.fillOval(170, 200, 30, 30);
20. g.drawArc(90, 150, 30, 30, 30, 270);
21. g.fillArc(270, 150, 30, 30, 0, 180);
22. }
23. }

Execute the above code by using the following commands:

Remote Applet

A remote applet is designed and developed by another developer. It is located or available on a remote
computer that is connected to the internet. In order to run the applet stored in the remote computer, our
system is connected to the internet then we can download run it. In order to locate and load a remote applet,
we must know the applet's address on the web that is referred to as Uniform Recourse Locator(URL).

Specifying Remote applet


1. <applet
2. codebase = "http://www.myconnect.com/applets/"
3. code = "FaceApplet.class"
4. width = 120
5. height =120>
6. </applet>

 Difference Between Local Applet and Remote Applet

The following table describes the key differences between Local applet and Remote applet.

Local Applet Remote Applet

There is no need to define the Applet's URL in Local We need to define the Applet's URL in
Applet. Remote Applet.

Local Applet is available on our computer. Remote Applet is not available on our
computer.

In order to use it or access it, we don't need Internet In order to use it or access it on our
Connection. computer, we need an Internet
Connection.

It is written on our own and then embedded into the web It was written by another developer.
pages.

We don't need to download it. It is available on a remote computer, so


we need to download it to our system.
 Differentiate application and applet

Parameters Java Application Java Applet

Applications are just like a Java Applets are small Java programs that are
program that can be executed designed to be included with the HTML web
Definition
independently without using the web document. They require a Java-enabled web
browser. browser for execution.

The applet does not require the main()


main () The application program requires a
method for its execution instead init() method
method main() method for its execution.
is required.

The “javac” command is used to


Applet programs are compiled with the
compile application programs, which
Compilation “javac” command and run using either the
are then executed using the “java”
“appletviewer” command or the web browser.
command.

Java application programs have full


Applets don’t have local disk and network
File access access to the local file system and
access.
network.

Applets can only access browser-specific


Applications can access all kinds of
Access level services. They don’t have access to the local
resources available on the system.
system.

First and foremost, the installation of


The Java applet does not need to be installed
Installation a Java application on the local
beforehand.
computer is required.

Applications can execute the Applets cannot execute programs from the
Execution
programs from the local system. local machine.

An application program is needed to


An applet program is needed to perform small
Program perform some tasks directly for the
tasks or part of them.
user.

It cannot run on its own; it needs JRE It cannot start on its own, but it can be
Run
to execute. executed using a Java-enabled web browser.

Connection Connectivity with other servers is


It is unable to connect to other servers.
with servers possible.

Read and It supports the reading and writing of It does not support the reading and writing of
Write files on the local computer. files on the local computer.
Parameters Java Application Java Applet

Operation

Application can access the system’s Executed in a more restricted environment


Security data and resources without any with tighter security. They can only use
security limitations. services that are exclusive to their browser.

Java applications are self-contained


Applet programs cannot run on their own,
Restrictions and require no additional security
necessitating the maximum level of security.
because they are trusted.

 Applet Life Cycle in Java

In Java, an applet is a special type of program embedded in the web page to generate dynamic content.
Applet is a class in Java.

The applet life cycle can be defined as the process of how the object is created, started, stopped, and
destroyed during the entire execution of its application. It basically has five core methods namely init(), start(),
stop(), paint() and destroy().These methods are invoked by the browser to execute.

Along with the browser, the applet also works on the client side, thus having less processing time.

Methods of Applet Life Cycle

There are five methods of an applet life cycle, and they are:

o init(): The init() method is the first method to run that initializes the applet. It can be invoked only once
at the time of initialization. The web browser creates the initialized objects, i.e., the web browser
(after checking the security settings) runs the init() method within the applet.
o start(): The start() method contains the actual code of the applet and starts the applet. It is invoked
immediately after the init() method is invoked. Every time the browser is loaded or refreshed, the
start() method is invoked. It is also invoked whenever the applet is maximized, restored, or moving
from one tab to another in the browser. It is in an inactive state until the init() method is invoked.
o stop(): The stop() method stops the execution of the applet. The stop () method is invoked whenever
the applet is stopped, minimized, or moving from one tab to another in the browser, the stop()
method is invoked. When we go back to that page, the start() method is invoked again.
o destroy(): The destroy() method destroys the applet after its work is done. It is invoked when the
applet window is closed or when the tab containing the webpage is closed. It removes the applet
object from memory and is executed only once. We cannot start the applet once it is destroyed.
o paint(): The paint() method belongs to the Graphics class in Java. It is used to draw shapes like circle,
square, trapezium, etc., in the applet. It is executed after the start() method and when the browser or
applet windows are resized.

Sequence of method execution when an applet is executed:

1. init()
2. start()
3. paint()

Sequence of method execution when an applet is executed:

1. stop()
2. destroy()

Applet Life Cycle Working

o The Java plug-in software is responsible for managing the life cycle of an applet.
o An applet is a Java application executed in any web browser and works on the client-side. It doesn't
have the main() method because it runs in the browser. It is thus created to be placed on an HTML
page.
o The init(), start(), stop() and destroy() methods belongs to the applet.Applet class.
o The paint() method belongs to the awt.Component class.
o In Java, if we want to make a class an Applet class, we need to extend the Applet
o Whenever we create an applet, we are creating the instance of the existing Applet class. And thus, we
can use all the methods of that class.

Flow of Applet Life Cycle:

These methods are invoked by the browser automatically. There is no need to call them explicitly.
Syntax of entire Applet Life Cycle in Java

1. class TestAppletLifeCycle extends Applet {


2. public void init() {
3. // initialized objects
4. }
5. public void start() {
6. // code to start the applet
7. }
8. public void paint(Graphics graphics) {
9. // draw the shapes
10. }
11. public void stop() {
12. // code to stop the applet
13. }
14. public void destroy() {
15. // code to destroy the applet
16. }
17. }

 Creating A Basic Applet in Java


1. Write the Java Applet Code. Create a new Java file and paste the following code: ...
2. Compile the Applet. Use the javac command in your terminal or command prompt to compile the file: ...
3. Create an HTML File to Host the Applet. Now, you need an HTML file that can call the applet: ...
4. View the Applet.
 Applet Architecture in Java
1. init(): This method is called when an applet is initialized. ...
2. start(): Invoked after the init() method or when the applet is revisited. ...
3. stop(): Called when the applet is no longer visible or needs to stop its operations.
4. destroy(): Invoked when the applet is about to be unloaded or destroyed.

5. /*Java Program to Create a Basic Applet*/


6. import java.applet.*;
7. import java.awt.*;
8. public class Basic_Applet extends Applet
9. {
10. //Function to initialize the applet
11. public void init()
12. {
13. setBackground(Color.white);
14. setLayout(new FlowLayout(FlowLayout.CENTER));
15. }
16. //Function to draw the string
17. public void paint(Graphics g)
18. {
19. g.drawString("Hello World",100,200);
20. }
21. }
22. /*
23. <applet code=Basic_Applet.class width=400 height=400>
24. </applet>
25. */

The Simplest Possible <APPLET> Tag - The above tag tells the browser or applet viewer to load the applet
whose Applet subclass, named AppletSubclass, is in a class file in the same directory as the HTML document
that contains the tag. The above tag also specifies the width and height in pixels of the applet.

HelloWorld.java

package openDis.applet;

import java.awt.Graphics;

public class HelloWorld extends java.applet.Applet {


public void init() {
resize(150,25);
}

public void paint(Graphics g) {


g.drawString("Hello world!", 50, 25);
}
}

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

Parameter in Applet

We can get any information from the HTML file as a parameter. For this purpose, Applet class provides a
method named getParameter(). Syntax:

1. public String getParameter(String parameterName)

Example of using parameter in Applet:

1. import java.applet.Applet;
2. import java.awt.Graphics;
3. public class UseParam extends Applet{
4. public void paint(Graphics g){
5. String str=getParameter("msg");
6. g.drawString(str,50, 50);
7. }
8. }

myapplet.html
1. <html>
2. <body>
3. <applet code="UseParam.class" width="300" height="300">
4. <param name="msg" value="Welcome to applet">
5. </applet>
6. </body>
7. </html>

You might also like