0% found this document useful (0 votes)
11 views

Unit 3 WT

Uploaded by

Krishna Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Unit 3 WT

Uploaded by

Krishna Sharma
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 8

Unit – 3

Scripting & Networking

1 Java script: Introduction, documents, forms, To include JavaScript in HTML document, you must
statements, functions, Objects enclose it inside <Script>…</Script> tag, you must set
type attribute of script tag to text/JavaScript. You can write
script anywhere within HTML document but it is
Scripting
preferable to write it inside <Head> … </Head> tags.
JavaScript is an object-based scripting language which is
lightweight and cross-platform. Example:
javaScript is an object-oriented language that allows
< HTML>
creation of interactive Web Pages. JavaScript allows user
<HEAD>
entries, which are loaded into an HTML form to be
processed as required. This empowers a web site to return <TITLE>Home Page</TITLE> <SCRIPT type =
site information according to a user’s requests. “text/javascript”>
JavaScript is not a compiled language, but it is a translated // JavaScript Statements…
</SCRIPT>
language. The JavaScript Translator (embedded in the
browser) is responsible for translating the JavaScript code </HEAD>
for the web browser. <BODY> </BODY>
JavaScript is a dynamic programming language for </HTML>
computers. It is a lightweight component of web pages
whose implementations allow client-side scripts to Features of JavaScript
communicate with users and create dynamic pages. It's an There are following features of JavaScript:
object-oriented programming language that can be
interpreted. 1. All popular web browsers support JavaScript as
JavaScript is a lightweight, cross-platform object-based they provide built-in execution environments.
scripting language. 2. JavaScript follows the syntax and structure of the
JavaScript is a translated language, not a compiled C programming language. Thus, it is a structured
language. The JavaScript Translator (which is built into programming language.
the browser) is in charge of translating JavaScript code for 3. JavaScript is a weakly typed language, where
web browsers. certain types are implicitly cast (depending on the
JavaScript (js) is a lightweight object-oriented operation).
programming language that is used to script webpages by a 4. JavaScript is an object-oriented programming
number of websites. When applied to an HTML document, language that uses prototypes rather than using
it is an interpreted, full-featured programming language classes for inheritance.
that enables dynamic interactivity on websites. 5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
It was first released in 1995 to enable users to add 7. JavaScript is supportable in several operating
programs to webpages in the Netscape Navigator browser. systems including, Windows, macOS, etc.
Since then, all other graphical web browsers have followed 8. It provides good control to the users over the web
it. Users can use JavaScript to create modern web browsers.
applications that communicate directly without having to
reload the page every time. Js is used on a typical website Application of JavaScript
to include various ways of interactivity and simplicity. JavaScript is used to create interactive websites. It is
mainly used for:
Steps for writing and executing JavaScript
o Client-side validation,
1) Write HTML And script code into source document
o Dynamic drop-down menus,
in a text editor o Displaying date and time,
2) Save the source document file o Displaying pop-up windows and dialog boxes
3) Open any browser and open source document in (like an alert dialog box, confirm dialog box and
browser and view output prompt dialog box),
Please note that, if you made any change in your source
o Displaying clocks etc.
document then you must save it then refresh browser to
view the changes.

The <Script> Tag


The Document interface represents any web page loaded in
the browser and acts as a portal to the web page's content,
Documents which is represented by the DOM tree. The DOM tree

ER.VIPIN RAWAT ASSISTANT PROFESSOR CSE DEAPARTMENT AIMT LUCKNOW Page 1


contains a variety of elements, including and. It gives the }
document global features, such as how to get the page's
URL and add new elements to the document. Objects
The Paper interface defines the properties and methods A javaScript object is a state and behavior-based entity
that are common to all types of documents. A wider API is (properties and method). For example, a car, a pen, a
accessible depending on the document type (e.g., HTML, bicycle, a chair, a bottle, a keyboard, and a monitor.
XML, SVG, etc.): The HTMLDocument interface is also
implemented by HTML documents served with the JavaScript is an object-oriented programming language. In
JavaScript, everything is an entity.
"text/html" content form, while the XMLDocument
interface is implemented by XML and SVG documents.
Forms JavaScript is a template-based language, not a class-based
JavaScript is capable of validating HTML forms.
language. To get the object, we don't need to build a class.
This function alerts a message and returns false if a form
However, we guide the creation of things.
field (fname) is empty, preventing the form from being
submitted:
Example:
Creating objects
Objects can be made in three different ways.
function validateForm () {
var x = document.forms["myForm”] ["fname"].value; By object literal
if (x == "") {
The following is the syntax for constructing an
alert ("Name must be filled out");
object with an object literal:
return false; object= {property1:value1, property 2:
} value2....propertyN:valueN}
}
Statements 2. By creating instance of Object directly (using new
These programming instructions are known as statements
keyword)
in a programming language.
A list of programming statements makes up a JavaScript
program. The syntax for explicitly constructing an object is
Values, Operators, Expressions, Keywords, and Comments as follows:
make up JavaScript statements.
Example: var objectname=new Object ();
var a, b, c; // Statement 1
x = 8; // Statement 2 3. By using an object constructor (using new
y = 4; // Statement 3 keyword)
z = x + y; // Statement 4
Functions You must construct a function with arguments in
A JavaScript function is a piece of code that performs a this case. This keyword can be used to assign
specific task. each argument value to the current object.
When "something" calls a JavaScript method, it is
The current object is referred to by this keyword.
executed (calls it).
The function keyword is used to describe a JavaScript
function, which is then followed by a name and Key takeaway:
parentheses (). JavaScript is a dynamic programming language for
computers.
JavaScript is a lightweight, cross-platform object-based
Letters, numbers, underscores, and dollar signs can all be
scripting language.
used in function names (same rules as variables).
It was first released in 1995 to enable users to add
programs to webpages in the Netscape Navigator browser.
Parameter names separated by commas can be used in the A JavaScript function is a piece of code that performs a
parentheses: (parameter1, parameter2, ...) specific task.
A javaScript object is a state and behavior-based entity.
The function's code to be executed is enclosed in curly
brackets: {}
2 Introduction to AJAX
function name (parameter1, parameter2, parameter3) { The acronym Ajax stands for
Asynchronous JavaScript and XML. It's used to connect
// code to be executed with the server without having to refresh the tab, resulting
in a better user experience and efficiency.

ER.VIPIN RAWAT ASSISTANT PROFESSOR CSE DEAPARTMENT AIMT LUCKNOW Page 2


It's a set of technologies that work together, such as An IP stands for internet protocol. An IP address is
JavaScript, DOM, XML, HTML/XHTML, CSS, and assigned to each device connected to a network. Each
XMLHttpRequest. device uses an IP address for communication. It also
behaves as an identifier as this address is used to identify
You can use AJAX to send and receive data the device on a network. It defines the technical format of
asynchronously without having to reload the tab. As a the packets. Mainly, both the networks, i.e., IP and TCP,
result, it is fast. are combined together, so together, they are referred to as
You may use AJAX to send only the most relevant TCP/IP. It creates a virtual connection between the source
information to the server, rather than the whole page. As a and the destination.
result, only the most important data from the client is sent
to the server. It improves the interactivity and speed of We can also define an IP address as a numeric address
your application. assigned to each device on a network. An IP address is
assigned to each device so that the device on a network
can be identified uniquely. To facilitate the routing of
packets, TCP/IP protocol uses a 32-bit logical address
Yahoo, Facebook, Twitter, Google Maps, and YouTube known as IPv4(Internet Protocol version 4).
are only a few examples of web applications that use ajax
technology. Function:

The internet protocol's main purpose is to provide hosts


with addresses, encapsulate data into packet structures, and
AJAX is a web-based application that employs a mixture route data from source to destination through one or more
of: IP networks. The internet protocol provides two main
items in order to achieve these functionalities, which are
mentioned below.
● XMLHttpRequest object (to exchange data
asynchronously with a server)
● Format of IP packet
● JavaScript/DOM (to display/interact with the
information) ● IP Addressing system

● CSS (to style the data) IP packet

● XML (often used as the format for transferring data) Until an IP packet is sent over the network, it contains two
main components: a header and a payload.

Fig 1: working of AJAX

Key takeaway: Fig 2: IP packet


The acronym Ajax stands for An IP header provides a lot of details about the IP packet,
Asynchronous JavaScript and XML. such as:
You can use AJAX to send and receive data ● The source IP address is that of the person who is
asynchronously without having to reload the tab. As a sending the data.
result, it is fast. ● IP address of the destination: The destination is a host
that collects data from the sender.
● Header length
● Packet length
3 Networking: Internet Addressing

ER.VIPIN RAWAT ASSISTANT PROFESSOR CSE DEAPARTMENT AIMT LUCKNOW Page 3


● TTL (Time to Live) of a packet is the amount of hops
that must occur before the packet is discarded.
● The internet protocol's transport protocol, which can 5 Factory Methods
be TCP or UDP, is known as the transport protocol.
The IP header contains a total of 14 fields, one of which is There are no visible constructors in the InetAddress class.
optional.
You must use one of the available factory methods to build
4 InetAddress an InetAddress object. Static methods in a class that return
Both the numerical IP address and the domain name for an instance of that class are known as factory methods.
that address are encapsulated in the InetAddress class. This
When having specific method names makes the results
class is interacted with by using an IP host's name, which
much simpler, this is achieved instead of overloading a
is more convenient and understandable than its IP address. constructor with different parameter lists. Here are three
The number is hidden within the InetAddress class. Both widely used InetAddress factory methods:
IPv4 and IPv6 addresses are supported by InetAddress.
The java.net framework. The IP address is encapsulated in
Java's InetAddress class. Most other networking classes,
such as Socket, ServerSocket, URL, DatagramSocket, The InetAddress object that represents the local host is
DatagramPacket, and others, use it. returned by the getLocalHost () process. For a host name
public final class InetAddress extends Object implements passed to it, the getByName () method returns an
Serializable InetAddress.
This class has two fields that represent an Internet address: On the Internet, it's popular to see a single name
hostName (a String) and address (an int). The name of the representing several machines. This is one way to have a
host is included in hostName. degree of scaling in the world of web servers. The factory
Creating New InetAddress Objects method getAllByName( ) returns an array of
The InetAddress class does not have any public InetAddresses that represents all of the addresses that a
constructors. InetAddress, on the other hand, has three given name resolves to. If it can't resolve the name to at
static methods that, given a little detail, return least one address, it'll throw an UnknownHostException.
appropriately initialized InetAddress items. They are as The factory method getByAddress( ), which takes an IP
follows: address and returns an InetAddress object, is also included
public static InetAddress InetAddress.getByName(String in InetAddress. You can use either an IPv4 or IPv6
hostName) address.
throws UnknownHostException The addresses and names of the local computer, as well as
public static InetAddress [] two Internet web pages.
InetAddress.getAllByName(String hostName)
throws UnknownHostException // Demonstrate InetAddress.
public static InetAddress InetAddress.getLocalHost() import java.net.*;
throws UnknownHostException
class InetAddressTest
To fill out the information in the InetAddress object, all {
three of these may link to the local DNS server. public static void main (String args []) throws
UnknownHostException {
InetAddress Address = InetAddress.getLocalHost();
Method Description System.out.println(Address);
Address =
InetAddress.getByName("www.HerbSchildt.com");
public static It returns an instance of System.out.println(Address);
InetAddress getByName InetAddress with the IP and InetAddress SW [] =
(String host) throws name of the LocalHost. InetAddress.getAllByName("www.nba.com"); for (int
UnknownHostException i=0; i<SW.length; i++)
System.out.println(SW[i]);
}
public static It returns an InetAddress }
InetAddress getLocalHost () instance with the local host
throws name and address.
UnknownHostException 6 Instance Methods
There are some other methods in the InetAddress class that
public String getHostName It returns the can be used on the objects returned by the methods. Here
() IP addresses hostname. are a few of the most common methods:

boolean equals (Object other): Returns true if this object


public The IP address is returned has the same Internet address as other.
String getHostAddress () as a string.

ER.VIPIN RAWAT ASSISTANT PROFESSOR CSE DEAPARTMENT AIMT LUCKNOW Page 4


byte [ ] getAddress( ) : Returns a byte array that represents wait for clients to communicate before proceeding. As a
the object’s IP address in network byte order. result, ServerSocket is only for servers. Clients use the
Socket class. Its purpose is to establish connections to
String getHostAddress( ) : Returns a string that represents server sockets and initiate protocol exchanges.
the host address associated with the InetAddress object.
Methods to Create TCP Client Sockets
String getHostName( ) : Returns a string that represents
the host name associated with the InetAddress object. These methods can be used to build a Socket class object:
boolean isMulticastAddress( ) : Returns true if this
address is a multicast address. Otherwise, it returns false. ● By using the following hostname and port number:

String toString( ) : Returns a string that lists the host Socket (String hostname1, int port1)
name and the IP address for convenience.
Where hostname1 is a string style variable referring to the
destination address, and port1 is the destination address's
port number. In the event of an error, this method will
throw the UnknownHostException or IOException
exceptions.

● By using the following syntax to define an


InetAddress object and a port number:

Socket (InetAddress ipaddr1, int port1)


Fig 3: methods
Where ipaddr1 is an item of the InetAddress class, and
A sequence of hierarchically cached servers is used to look port1 is the destination's port number. In the event of an
up Internet addresses. That means your local computer can error, this method will throw the IOException exception.
automatically recognize a specific name-to-IP-address
mapping, such as for itself and nearby servers. It can ask a Method of the Socket Class
local DNS server for IP address information for other InetAddress getInetAddress() -- Returns the InetAddress
names. If that server doesn't have a specific address, it may that is associated with the socket object.
request one from a remote location. This procedure can be int getPort() -- Returns the port number on which the
followed all the way to the root server. socket is connected
int getLocalPort() -- Returns the local port number on
Key takeaway: which the socket is created
There are some other methods in the InetAddress class
that can be used on the objects returned by the methods. InputStream getInputStream() -- Returns the InputStream
A sequence of hierarchically cached servers is used to associated with the calling object.
look up Internet addresses.
OutputStream getOutputStream() -- Returns the
OutputStream associated with the calling object.

void close () -- Closes the InputStream ()


7 TCP/IP Client Sockets and OutputStream () of the socket.

A TCP/IP client socket connects two computers on a Example: Client Side Code
network in a secure, bi-directional, stream-based link. An import java.net.*;
instance of the Socket class is used to implement the client import java.io.*;
socket. Its aim is to establish a connection to the server and class clientsock
initiate protocol exchanges. {
public static void main (String args []) throws
TCP/IP sockets are used to create stable, bidirectional, IOException
permanent, point-to-point, stream-based connections {
between Internet hosts. A socket connects Java's I/O System.out.println("sending request to server....");
device to other programs running on the local computer or Socket client=new Socket ("127.0.0.1",1235);
on some other machine connected to the Internet. System.out.println("successfully connected");
BufferedReader br1=new BufferedReader
In Java, there are two types of TCP sockets. The first is for (new InputStreamReader (System.in));
servers, and the second is for clients. The ServerSocket PrintStream ps=new
class is intended to function as a "listener," meaning it will PrintStream(client.getOutputStream());

ER.VIPIN RAWAT ASSISTANT PROFESSOR CSE DEAPARTMENT AIMT LUCKNOW Page 5


BufferedReader br=new BufferedReader (new
InputStreamReader(client.getInputStream()));
while(true) URL (URL context, String spec, URLStreamHandler
{ handler)
System.out.println("input the data u want to send to echo
server: "); By parsing the given spec with the specified handler
String s=br1.readLine(); within a given context, this method creates an instance of a
ps.println(s); URL.
if(s.equals("exit"))
{
System.exit(1);
}
String st=br.readLine();
System.out.println("data returned by the server: ");
System.out.println(st);
}
} URL Connection
}
A communication link between the URL and the
application is represented by the Java URLConnection
8 URL, URL Connection class. This class can be used to read and write data to the
URL-referenced resource defined.
The Uniform Resource Locator (URL) is a format for
specifying addresses on the World Wide Web. A URL is
the most basic network identifier for any resource on the An active link to a resource defined by a URL is
internet (e.g., hypertext pages, images, and sound files). represented by the abstract class URLConnection. The
URLConnection class serves two distinct but
The URL is a relatively comprehensible format for complementary purposes. For starters, it gives you more
identifying or addressing information on the Internet. control over how you communicate with a server than the
URLs are everywhere; they're used by every browser to URL class does. You may inspect the MIME headers sent
find information on the Internet. The URL class in Java's by an HTTP server and react appropriately using a
network class library provides an easy, succinct API for URLConnection.
accessing information over the Internet via URLs.
The MIME header fields used in the client request may be
modified. A URLConnection can be used to import binary
files. Finally, a URLConnection allows you to use POST
An URL is represented by the Java URL class. Uniform and PUT to send data back to a web server, as well as
Resource Locator is an acronym for Uniform Resource other HTTP request methods.
Locator. It directs you to a World Wide Web resource.
Second, like the URLStreamHandler class, the
URLConnection class is part of Java's protocol handler
Constructor of java URL Class mechanism. Protocol handlers have a basic concept: they
URL (string spec) distinguish the details of processing a protocol from the
From the String representation, creates an instance of a details of processing specific data types, providing user
URL. interfaces, and other tasks that a monolithic web browser
URL (String protocol, String host, int port, String file) performs. Java.net is the foundation.
From the specified protocol, host, port number, and file,
creates an instance of a URL. The URLConnection class is abstract; you must create a
URL (String protocol, String host, int port, String file, subclass to enforce a particular protocol. These subclasses
URLStreamHandler handler) may be loaded at runtime by your own applications or
Creates a URL from the protocol, host, port number, file,
the HotJava browser; in the future, Java applications will
and handler arguments.
be able to download protocol handlers as required over the
Internet, allowing them to be automatically extensible.
URL (String protocol, String host, String file)
From the specified protocol name, host name, and file
name, creates an instance of a URL.
How to get the object of URLConnection class
URL (URL context, String spec)
The URL class's openConnection () method returns a
By parsing the given spec within a given context, this URLConnection item. The syntax is as follows:
method creates an instance of a URL.

ER.VIPIN RAWAT ASSISTANT PROFESSOR CSE DEAPARTMENT AIMT LUCKNOW Page 6


public URLConnection openConnection A communication link between the URL and the
() throws IOException {} application is represented by the Java URLConnection
class.
This class can be used to read and write data to the
URL-referenced resource defined.
Displaying source code of a webpage by URLConnecton
class 9 TCP/IP Server Sockets

Using the getInputStream () method of the For server applications, Java has a separate socket class
URLConnection class, we may show all of the data from a that must be used. The ServerSocket class is used to build
webpage. The getInputStream () method returns all of the servers that listen on published ports for connections from
data in the stream that can be read and displayed for the local or remote client programs. Server Sockets are not the
given URL. same as regular Sockets.

When you build a ServerSocket, it will inform the device


that it is interested in receiving client connections. Server
Socket’s constructors represent the port number on which
Example:
you want to accept connections and, optionally, the length
of the queue for that port.
import java.io.*;
The queue length informs the machine how many pending
import java.net.*; client connections it will keep before simply rejecting
them. The default is 50. Under certain circumstances, the
public class URLConnectionExample { constructors can throw an IOException.

public static void main (String [] args) { Three of its constructors are as follows:

try {

URL url=new
URL("http://www.javatpoint.com/java-tutorial");

URLConnection urlcon=url.openConnection();
Fig 4: constructor
InputStream stream=urlcon.getInputStream();
Accept () is a blocking method on ServerSocket that waits
int i; for a client to initiate communication before returning with
a regular Socket that can be used to communicate with the
while((i=stream.read())! =-1) { client.

System.out.print((char)i); 10 Datagram

} TCP/IP networking is suitable for the majority of


networking requirements. It generates a stream of packet
}catch(Exception e){System.out.println(e);} data that is serialized, predictable, and dependable.
However, there is a price to pay for this. TCP requires a
number of complex algorithms for congestion management
}
on congested networks, as well as negative packet loss
predictions. As a result, data is transported in an inefficient
} manner. Datagrams are a different choice.

Datagrams are information packets that are sent between


computers. They resemble a hard throw to the third
Key takeaway: baseman from a well-trained yet blindfolded catcher.
The Uniform Resource Locator (URL) is a format for
specifying addresses on the World Wide Web. There is no guarantee that the datagram will arrive at its
A URL is the most basic network identifier for any intended destination or that anyone will be there to catch it
resource on the internet. after it has been posted. Similarly, there is no guarantee
that the datagram was not destroyed in transit or that the

ER.VIPIN RAWAT ASSISTANT PROFESSOR CSE DEAPARTMENT AIMT LUCKNOW Page 7


person who sent it is still alive to receive an answer when
it is received.

Java uses two groups to implement datagrams on top of


the UDP protocol: the DatagramPacket object is the data
container, and the DatagramSocket is the mechanism for
sending and receiving Datagram Packets.

DatagramSocket
DatagramSocket defines four public constructors. They are
shown here: DatagramSocket () throws SocketException

DatagramSocket (int port) throws SocketException


DatagramSocket (int port, InetAddress ipAddress) throws
SocketException DatagramSocket (SocketAddress
address) throws SocketException
The first creates a DatagramSocket on the local machine
that is connected to any unused port. The second generates
a DatagramSocket with port as its destination. The third
creates a DatagramSocket with the required InetAddress
and port. The fourth creates a

The required SocketAddress is bound to the


DatagramSocket. The concrete class InetSocketAddress
implements the abstract class SocketAddress.
InetSocketAddress encapsulates a port number and an IP
address. If an error occurs when making the socket, both of
them may throw a SocketException.

Many methods are described by DatagramSocket. Send ()


and receive (), two of the most common, are seen here:

void send (DatagramPacket packet) throws IOException


void receive (DatagramPacket packet) throws IOException

Fig 5: other method of datagram socket

ER.VIPIN RAWAT ASSISTANT PROFESSOR CSE DEAPARTMENT AIMT LUCKNOW Page 8

You might also like