You are on page 1of 135

Ajay Kumar Garg Engineering College, Ghaziabad

(College Code: 027)

Web Technologies
Unit 3
Java Script

Dr. Ruchi Gupta


Associate Professor
Department of Information Technology
10/26/2023
• UNIT-3 Scripting: Java script: Introduction, documents, forms,
statements, functions, objects; introduction to AJAX, Networking :
Internet Addressing, InetAddress, Factory Methods, Instance
Methods, TCP/IP Client Sockets, URL, URL Connection, TCP/IP Server
Sockets, Datagram.
• JavaScript (js) is a light-weight object-oriented programming language
which is used by several websites for scripting the webpages.
• JavaScript is not a compiled language, but it is a translated language.
The JavaScript Translator (embedded in the browser) is responsible
for translating the JavaScript code for the web browser.
• It is an interpreted, full-fledged programming language that enables
dynamic interactivity on websites when applied to an HTML
document.
• It was introduced in the year 1995 for adding programs to the
webpages in the Netscape Navigator browser.
JavaScript

• it has been adopted by all other graphical web browsers.


• With JavaScript, users can build modern web applications to interact
directly without reloading the page every time.
• The traditional website uses js to provide several forms of interactivity
and simplicity.
• JavaScript is used to create client-side dynamic pages.
• JavaScript is a weakly typed language (dynamically typed).
JavaScript can be used for Client-side developments as well
as Server-side developments.
• Client-side: It supplies objects to control a browser and its Document Object Model (DOM). Like if
client-side extensions allow an application to place elements on an HTML form and respond to user
events such as mouse clicks, form input, and page navigation. Useful libraries for the client side
are AngularJS, ReactJS, VueJS, and so many others.
• Server-side: It supplies objects relevant to running JavaScript on a server. For if the server-side
extensions allow an application to communicate with a database, and provide continuity of
information from one invocation to another of the application, or perform file manipulations on a
server. The useful framework which is the most famous these days is node.js.
• Imperative language – In this type of language we are mostly concerned about how it is to be done.
It simply controls the flow of computation. The procedural programming approach, object, oriented
approach comes under this as async await we are thinking about what is to be done further after the
async call.
• Declarative programming – In this type of language we are concerned about how it is to be done,
basically here logical computation requires. Her main goal is to describe the desired result without
direct dictation on how to get it as the arrow function does.
Why JavaScript is known as a lightweight
programming language ?
• JavaScript is considered lightweight due to the fact that it has low
CPU usage, is easy to implement, and has a minimalist syntax.
Minimalist syntax as in, has no data types.
• Everything is treated here as an object. It is very easy to learn
because of its syntax similar to C++ and Java.
• A lightweight language does not consume much of your CPU’s
resources. It doesn’t put excess strain on your CPU or RAM.
• JavaScript runs in the browser even though it has complex paradigms
and logic which means it uses fewer resources than other languages.
Features of JavaScript
1. All popular web browsers support JavaScript as they provide built-in execution
environments.
2. JavaScript follows the syntax and structure of the C programming language.
Thus, it is a structured programming language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast
(depending on the operation).
4. JavaScript is an object-oriented programming language that uses prototypes
rather than using classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including, Windows,
macOS, etc.
8. It provides good control to the users over the web browsers.
Application of JavaScript
• Web Development: Adding interactivity and behavior to static sites JavaScript was
invented to do this in 1995. By using AngularJS that can be achieved so easily.
• Web Applications: With technology, browsers have improved to the extent that a
language was required to create robust web applications. When we explore a map in
Google Maps then we only need to click and drag the mouse. All detailed view is just a
click away, and this is possible only because of JavaScript. It uses Application
Programming Interfaces(APIs) that provide extra power to the code. The Electron and
React are helpful in this department.
• Server Applications: With the help of Node.js, JavaScript made its way from client to
server and Node.js is the most powerful on the server side.
• Games: Not only in websites, but JavaScript also helps in creating games for leisure. The
combination of JavaScript and HTML 5 makes JavaScript popular in game development as
well. It provides the EaseJS library which provides solutions for working with rich
graphics.
• Smartwatches: JavaScript is being used in all possible devices and applications. It
provides a library PebbleJS which is used in smartwatch applications. This
framework works for applications that require the Internet for their functioning.
• Art: Artists and designers can create whatever they want using JavaScript to draw
on HTML 5 canvas, and make the sound more effective also can be
used p5.js library.
• Machine Learning: This JavaScript ml5.js library can be used in web
development by using machine learning.
• Mobile Applications: JavaScript can also be used to build an application for
non-web contexts. The features and uses of JavaScript make it a powerful tool for
creating mobile applications. This is a Framework for building web and mobile
apps using JavaScript. Using React Native, we can build mobile applications for
different operating systems. We do not require to write code for different systems.
Write once use it anywhere!
Limitations of JavaScript
• Security risks: JavaScript can be used to fetch data using AJAX or by manipulating tags
that load data such as <img>, <object>, <script>. These attacks are called cross-site script
attacks. They inject JS that is not part of the site into the visitor’s browser thus fetching the
details.
• Performance: JavaScript does not provide the same level of performance as offered by
many traditional languages as a complex program written in JavaScript would be
comparatively slow. But as JavaScript is used to perform simple tasks in a browser, so
performance is not considered a big restriction in its use.
• Complexity: To master a scripting language, programmers must have a thorough
knowledge of all the programming concepts, core language objects, and client and
server-side objects otherwise it would be difficult for them to write advanced scripts using
JavaScript.
• Weak error handling and type checking facilities: It is a weakly typed language as there
is no need to specify the data type of the variable. So wrong type checking is not performed
by compile.
How to Link JavaScript File in HTML ?
• JavaScript can be added to HTML file in two ways:
• Internal JS: We can add JavaScript directly to our HTML file by writing
the code inside the <script> tag. The <script> tag can either be placed inside
the <head> or the <body> tag according to the requirement.
• External JS: We can write JavaScript code in another files having an
extension.js and then link this file inside the <head> tag of the HTML file in
which we want to add this code.
• Syntax:
<script>
// JavaScript Code
</script>
Using JavaScript in your HTML

• JavaScript can be inserted into documents by using the SCRIPT


tag
<html>
<head>
<title>Hello World in JavaScript</title>
</head>
<body>
<script type="text/javascript">
document.write("Hello World!");
</script>
</body>
</html>

13
Add JavaScript Code inside Head Section
• JavaScript code is placed inside the head section of an HTML page
and the function is invoked when a button is clicked.
<!DOCTYPE html>
<html>

<head>
<title>
Add JavaScript Code inside Head Section
</title>

<script>
function myFun() {
document.getElementById("demo")
.innerHTML = "Content changed!";
}
</script>
</head>

<body>
<h2>
Add JavaScript Code
inside Head Section
</h2>

<h3 id="demo" style="color:green;">


Ruchi
</h3>

<button type="button" onclick="myFun()">


Click Here
</button>
</body>

</html>
Add JavaScript Code inside Body Section
• JavaScript Code is placed inside the body section of an HTML page
and the function is invoked when a button is clicked.
<!DOCTYPE html>
<html>

<head>
<title>
Add JavaScript Code inside Body Section
</title>
</head>

<body>
<h2>
Add JavaScript Code
inside Body Section
</h2>

<h3 id="demo" style="color:green;">


Ruchi
</h3>

<button type="button" onclick="myFun()">


Click Here
</button>

<script>
function myFun() {
External JavaScript

• JavaScript can also be used in external files. The file extension of the
JavaScript file will be .js.
• To use an external script put the name of the script file in the src
attribute of a script tag. External scripts cannot contain script tags.

External JavaScript References


We can reference an external script in three ways in javascript:
By using a full URL:
src = "https://www.geeksforgeek.org/js/script.js"
By using a file path:
src = "/js/script.js"
Without using any path:
src = "script.js"
JavaScript Can Change HTML Attribute Values
<!DOCTYPE html>
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p>JavaScript can change HTML attribute values.</p>

<p>In this case JavaScript changes the value of the src (source) attribute of an image.</p>

<button onclick="document.getElementById('myImage').src='pic_bulbon.gif'">Turn on the light</button>

<img id="myImage" src="pic_bulboff.gif" style="width:100px">

<button onclick="document.getElementById('myImage').src='pic_bulboff.gif'">Turn off the light</button>

</body>
</html>
JavaScript Example
1.<script>
2.document.write("Hello JavaScript by JavaScript");
3.</script>
The script tag specifies that we are using JavaScript.
The text/javascript is the content type that provides information to the browser about the
data.
The document.write() function is used to display dynamic content through JavaScript.
<html>
<head>
<script type="text/javascript">
function msg(){
alert("Hello Javatpoint"); }
</script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="click" onclick="msg()"/>
</form>
</body>
</html>
JavaScript Versions

Version Name Release Year Features

ES1 ECMAScript 1 1997 Initial Release

ES2 ECMAScript 2 1998 Minor Editorial Changes

Added:
•Regular Expression
ES3 ECMAScript 3 1999 •try/catch
•Exception Handling
•switch case and do-while

ES4 ECMAScript 4 Abandoned due to conflicts

Added:
•JavaScript “strict mode”
ES5 ECMAScript 5 2009
•JSON support
•JS getters and setters

Added:
•let and const
•Class declaration
ES6 ECMAScript 2015 2015
•import and export
•for..of loop
•Arrow functions

Added:
•Block scope for variable
ES7 ECMAScript 2016 2016 •async/await
•Array.includes function
•Exponentiation Operator

Added:
•Object.values
ES8 ECMAScript 2017 2017
•Object.entries
•Object.getOwnPropertiesDescriptors

Added:
ES9 ECMAScript 2018 2018 •spread operator
•rest parameters

Added:
•Array.flat()
ES10 ECMAScript 2019 2019
•Array.flatMap()
•Array.sort is now stable

Added:
ES11 ECMAScript 2020 2020 •BigInt primitive type
•nullish coalescing operator

Added:
ES12 ECMAScript 2021 2021 •String.replaceAll() Method
•Promise.any() Method

Added:
•Top-level await
ES13 ECMAScript 2022 2022
•New class elements
•Static block inside classes

ES.Next Dynamic name for upcoming versions


JavaScript Variables
• Variables are Containers for Storing Data.
• Containers provide an easy way to group objects, and control them
as one object.
• We can place data into these containers and then refer to the data simply
by naming the container.
• In JavaScript variable names are case sensitive i.e. a is different from A.
• Java script uses the keywords var, let, const to declare a variable.
• Variable name can only be started with a underscore ( _ ) or a letter (from a
to z or A to Z), or dollar ( $ ) sign.
• Numbers (0 to 9) can only be used after a letter.
• No other special character is allowed in variable name.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>

<p>In this example, x, y, and z are variables.</p>

<p id="demo"></p>

<script>
var x = 5;
var y = 6;
var z = x + y;
document.getElementById("demo").innerHTML =
"The value of z is: " + z;
</script>

</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Variables</h1>

<p>In this example, x, y, and z are variables.</p>

<p id="demo"></p>

<script>
let x = 5;
let y = 6;
let z = x + y;
document.getElementById("demo").innerHTML =
"The value of z is: " + z;
</script>

</body>
</html>
<!DOCTYPE html>

<html>

<body>

<h1>JavaScript Variables</h1>

<p>In this example, price1, price2, and total are variables.</p>

<p id="demo"></p>

<script>

const price1 = 5;

const price2 = 6;

let total = price1 + price2;

document.getElementById("demo").innerHTML =

"The total is: " + total;

</script>

</body>

</html>
JavaScript Operators and Constructs

• JavaScript has most of the operators we're used to from C/Java


•– Arithmetic (+, - , , /, %)
Assignment (=, +=, -=,
•–
•– Logical (&&, ||, !)
Comparison (<, >, <=, >=, ==)
•–
Note: + also does string concatentation

Constructs:

•– if, else, while, for, switch, case
Types of JavaScript Operators
• Arithmetic Operators
• Assignment Operators
• Comparison Operators
• String Operators
• Logical Operators
• Bitwise Operators
• Ternary Operators
• Type Operators
Arithmetic Operators
<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Arithmetic</h1>
<h2>The * Operator</h2>

<p id="demo"></p>

<script>
let x = 5;
let y = 2;
let z = x * y;
document.getElementById("demo").innerHTML = z;
</script>

</body>
</html>
Assignment Operators
<!DOCTYPE html>
<html>
<body>

<h1>JavaScript String Operators</h1>

<p>All conditional operators can be used on both numbers and strings.</p>

<p id="demo"></p>

<script>
let text1 = "A";
let text2 = "B";
let result = text1 < text2;
document.getElementById("demo").innerHTML = "Is A less than B? " + result;
</script>

</body>
</html>
JavaScript Functions

• A JavaScript function is a block of code designed to perform a particular task.


• A JavaScript function is executed when "something" invokes it (calls it).
• Function is a group of reusable statements (Code) that can be called any where in a
program. In javascript function keyword is used to declare or define a function.
Key Points
•To define a function use function keyword followed by functionname, followed by
parentheses ().
•In parenthesis, we define parameters or attributes.
•The group of reusabe statements (code) is enclosed in curly braces {}. This code is
executed whenever function is called.
Syntax:
function name(parameter1, parameter2, parameter3)
{
// code to be executed

}
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Functions</h2>

<p>This example calls a function which performs a calculation and returns the result:</p>

<p id="demo"></p>

<script>
var x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;

function myFunction(a, b)
{
return a * b;
}
</script>

</body>
</html>
<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Functions</h1>

<p>Call a function which performs a calculation and returns the result:</p>

<p id="demo"></p>

<script>
let x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;

function myFunction(a, b) {
return a * b;
}
</script>

</body>
</html>
Keyword Description
var Declares a variable
let Declares a block variable
const Declares a block constant
if JavaScript Keywords Marks a block of statements to be executed on a
JavaScript statements condition
often start with
switch
a keyword to identify Marks a block of statements to be executed in
the JavaScript action to different cases
for be performed. Marks a block of statements to be executed in a
loop
function Declares a function
return Exits a function
try Implements error handling to a block of
statements
Sr.No. Statement Description

1. switch case A block of statements in which execution of code depends upon different cases.
The interpreter checks each case against the value of the expression until a match
is found. If nothing matches, a default condition will be used.

2. If else The if statement is the fundamental control statement that allows JavaScript to
make decisions and execute statements conditionally.

3. While The purpose of a while loop is to execute a statement or code block repeatedly as
long as expression is true. Once expression becomes false, the loop will be exited.

4. do while Block of statements that are executed at least once and continues to be executed
while condition is true.

5. for Same as while but initialization, condition and increment/decrement is done in the
same line.

6. for in This loop is used to loop through an object's properties.

7. continue The continue statement tells the interpreter to immediately start the next iteration
of the loop and skip remaining code block.

8. break The break statement is used to exit a loop early, breaking out of the enclosing
curly braces.

9. function A function is a group of reusable code which can be called anywhere in your
programme. The keyword function is used to declare a function.

10. return Return statement is used to return a value from a function.

11. var Used to declare a variable.

12. try A block of statements on which error handling is implemented.

13. catch A block of statements that are executed when an error occur.

14. throw Used to throw an error.


JavaScript Objects
Objects are variables too. But objects can contain many values. The values are written as name:value pairs (name
and value separated by a colon).
The name:values pairs in JavaScript objects are called properties:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Objects</h2>
<p id="demo"></p>
<script>
// Create an object:
const car = {type:"Fiat", model:"500", color:"white"};

// Display some data from the object:


document.getElementById("demo").innerHTML = "The car type
is " + car.type;
</script>

</body>
</html>
JavaScript Statements
JavaScript statements are composed of:
Values, Operators, Expressions, Keywords, and Comments.
A JavaScript program is a list of programming statements.
JavaScript statements are the commands to tell the browser to what action to perform. Statements are
separated by semicolon (;).
In HTML, JavaScript programs are executed by the web browser.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Statements</h2>
<p>A <b>JavaScript program</b> is a list of <b>statements</b> to be executed by a computer.</p>
<p id="demo"></p>
<script>
let x, y, z; // Statement 1
x = 5; // Statement 2
y = 6; // Statement 3
z = x + y; // Statement 4
document.getElementById("demo").innerHTML ="The value of z is " + z + ".";
</script>
</body>
</html>
Output of this statement is given on the next slide
JavaScript Code Blocks
JavaScript statements can be grouped together in code blocks, inside curly brackets {...}.
The purpose of code blocks is to define statements to be executed together.

Example:-

<!DOCTYPE html>
<html>
<body
<h2>JavaScript Statements</h2>
<p>JavaScript code blocks are written between { and }</p>
<button type="button" onclick="myFunction()">Click Me!</button>
<p id="demo1"></p>
<p id="demo2"></p><script>
function myFunction() {
document.getElementById("demo1").innerHTML = "Hello Dolly!";
document.getElementById("demo2").innerHTML = "How are you?";
}
</script>
</body>
</html>
JavaScript Arrays
• An array is a special variable, which can hold more than one
value:
const cars = ["Saab", "Volvo", "BMW"];
• If you have a list of items (a list of car names, for example),
storing the cars in single variables could look like this:
let car1 = "Saab";
let car2 = "Volvo";
let car3 = "BMW";
JavaScript has arrays that are indexed starting at 0

• Using an array literal is the easiest way to create a
JavaScript Array.
<!DOCTYPE html>
<html>
<body>
<h1>JavaScript Arrays</h1>

<p id="demo"></p>

<script>
const cars = [
"Saab",
"Volvo",
"BMW"
];
document.getElementById("demo").innerHTML = cars;
</script>

</body>
</html>
JavaScript Objects
In JavaScript, Objects can be created using two different
methodologies namely Literal Form and Constructed Form.
•Literal Form: The literal form uses the construction of object
literals that can be said as a collection of key-value pairs enclosed
within a pair of curly braces. The syntaxial form is shown below.
let obj = { key1: value1,
key2: value2, ... };
•Constructed Form: The Constructed form uses either an object constructor function or the new
keyword to create an empty object ad then adds properties to the object one by one. The syntaxial
forms are shown below.
•Object Constructor Function: In this methodology, the user creates an explicit function to take
required values as parameters and assign them as the properties of the desired object.
function
obj(value1, value2, ...) {
this.key1 = value1;
this.key2 = value2; ... }
•Using New Keyword: This methodology uses the New keyword in front of any constructor method or
any built-in constructor method ( such as Object, Date, String, etc) and creates a new instance of the
following object by mounting it on memory.
let obj = new Object();
obj.key1 = value1;
obj.key2 = value2; ...
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Objects</h2>

<p id="demo"></p>

<script>
// Create an object:
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

// Display some data from the object:


document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old.";
</script>

</body>
</html>
Java Script Documents
• The HTML DOM document object is the owner of all other objects in
your web page. The document object represents the whole html
document.
• If you want to access any element in an HTML page, you always start
with accessing the document object.
• When html document is loaded in the browser, it becomes a
document object.
• It is the root element that represents the html document. It has
properties and methods.
• By the help of document object, we can add dynamic content to our
web page.
Finding HTML Elements

Method Description
document.getElementById(id) Find an element by element
id
document.getElementsByTagName(name) Find elements by tag name
document.getElementsByClassName(name) Find elements by class
name
Javascript - document.getElementById() method

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript HTML DOM</h2>

<p id="intro">Finding HTML Elements by Id</p>


<p>This example demonstrates the <b>getElementsById</b> method.</p>

<p id="demo"></p>

<script>
const element = document.getElementById("intro");

document.getElementById("demo").innerHTML =
"The text from the intro paragraph is: " + element.innerHTML;

</script>

</body>
</html>
Javascript - document.getElementsByTagName() method
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript HTML DOM</h2>

<p>Finding HTML Elements by Tag Name.</p>


<p>This example demonstrates the <b>getElementsByTagName</b> method.</p>

<p id="demo"></p>

<script>
const element = document.getElementsByTagName("p");

document.getElementById("demo").innerHTML = 'The text in first paragraph (index 0) is: '


+ element[0].innerHTML;

</script>

</body>
</html>
Javascript - document.getElementsByClass Name()
method
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript HTML DOM</h2>

<p>Finding HTML Elements by Class Name.</p>


<p class="intro">Hello World!</p>
<p class="intro">This example demonstrates the <b>getElementsByClassName</b> method.</p>

<p id="demo"></p>

<script>
const x = document.getElementsByClassName("intro");
document.getElementById("demo").innerHTML =
'The first paragraph (index 0) with class="intro" is: ' + x[0].innerHTML;
</script>

</body>
</html>
Changing HTML Elements

Property Description
element.innerHTML = new html content Change the inner HTML of an element
element.attribute = new value Change the attribute value of an HTML element
element.style.property = new style Change the style of an HTML element
Method Description
element.setAttribute(attribute, value) Change the attribute value of an HTML element
Adding and Deleting Elements

Method Description
document.createElement(element) Create an HTML element
document.removeChild(element) Remove an HTML element
document.appendChild(element) Add an HTML element
document.replaceChild(new, old) Replace an HTML element
document.write(text) Write into the HTML output stream
Adding Events Handlers

Method Description
document.getElementById(id).onclick Adding event handler
= function(){code} code to an onclick event
Finding HTML Objects

Property Description DOM


document.anchors Returns all <a> elements that have a name attribute 1

document.applets Deprecated 1

document.baseURI Returns the absolute base URI of the document 3

document.body Returns the <body> element 1

document.cookie Returns the document's cookie 1

document.doctype Returns the document's doctype 3

document.documentElement Returns the <html> element 3

document.documentMode Returns the mode used by the browser 3

document.documentURI Returns the URI of the document 3

document.domain Returns the domain name of the document server 1

document.domConfig Obsolete. 3

document.embeds Returns all <embed> elements 3

document.forms Returns all <form> elements 1

document.head Returns the <head> element 3

document.images Returns all <img> elements 1

document.implementation Returns the DOM implementation 3

document.inputEncoding Returns the document's encoding (character set) 3

document.lastModified Returns the date and time the document was updated 3

document.links Returns all <area> and <a> elements that have a href attribute 1

document.readyState Returns the (loading) status of the document 3

document.referrer Returns the URI of the referrer (the linking document) 1

document.scripts Returns all <script> elements 3

document.strictErrorChecking Returns if error checking is enforced 3

document.title Returns the <title> element 1

document.URL Returns the complete URL of the document


Forms

• Form name tag is used to define the name of the form. The name of the form here is "Login_form". This name
will be referenced in the JavaScript form.
• The action tag defines the action, and the browser will take to tackle the form when it is submitted. Here, we
have taken no action.
• The method to take action can be either post or get, which is used when the form is to be submitted to the
server. Both types of methods have their own properties and rules.
• The input type tag defines the type of inputs we want to create in our form. Here, we have used input type as
'text', which means we will input values as text in the textbox.
• Net, we have taken input type as 'password' and the input value will be password.
• Next, we have taken input type as 'button' where on clicking, we get the value of the form and get displayed.
• Referencing forms
• Now, we have created the form element using HTML, but we also need to make its connectivity to JavaScript.
For this, we use the getElementById () method that references the html form element to the JavaScript code.
• The syntax is as follows:
let form = document.getElementById('subscribe');
1.<html>
2.<head>
3.<title> Login Form</title>
4.</head>
5.<body>
6.<h3> LOGIN </h3>
7.<formform ="Login_form" onsubmit="submit_form()">
8.<h4> USERNAME</h4>
9.<input type="text" placeholder="Enter your email id"/>
10.<h4> PASSWORD</h4>
11.<input type="password" placeholder="Enter your password"/></br></br>
12.<input type="submit" value="Login“ onclick=“submit_form()”/>
13.<input type="button" value="SignUp" onClick="create()"/>
14.</form>
15.<script type="text/javascript">
16.function submit_form(){
17.alert("Login successfully");
18.}
19.function create(){
20.window.location="signup.html";
21.}
22.</script>
23.</body>
24.</html>
Inner HTML
When you use innerHTML, you can change the page's content without refreshing the page.
<script>
This can make your website feel quicker and more responsive to user input.

The innerHTML property can be used along with getElementById() within your JavaScript code
to refer to an HTML element and change its contents.
<script>
function Msg1(){
document.getElementById('myText').innerHTML = 'Hey <strong>Thanks!</strong>';
}
function Msg2(){
document.getElementById('myText').innerHTML = 'Try <strong>message 1</strong>
again...';
}
</script>
<input type="button" onclick="Msg1()" value="Show Message 1">
<input type="button" onclick="Msg2()" value="Show Message 2">
<p id="myText"></p>
Object Methods
Objects can also have methods.
Methods are actions that can be performed on objects.
Methods are stored in properties as function definitions.

Example
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};

A method is a function stored as a property.


Introduction To AJAX
• AJAX stands for Asynchronous JavaScript and XML.
• It is used to communicate with the server without refreshing the web page and
thus increasing the user experience and better performance.
• AJAX is a new technique for creating better, faster, and more interactive web
applications with the help of XML, HTML, CSS, and Java Script.
• Ajax uses XHTML for content, CSS for presentation, along with Document Object
Model and JavaScript for dynamic content display.
• Conventional web applications transmit information to and from the sever using
synchronous requests. It means you fill out a form, hit submit, and get directed to
a new page with new information from the server.
• With AJAX, when you hit submit, JavaScript will make a request to the server,
interpret the results, and update the current screen. In the purest sense, the user
would never know that anything was even transmitted to the server.
• XML is commonly used as the format for receiving server data,
although any format, including plain text, can be used.
• AJAX is a web browser technology independent of web server
software.
• A user can continue to use the application while the client program
requests information from the server in the background.
• Intuitive and natural user interaction. Clicking is not required, mouse
movement is a sufficient event trigger.
• Data-driven as opposed to page-driven.
Features of AJAX
• AJAX = Asynchronous JavaScript And XML.
• AJAX is not a programming language.
• AJAX just uses a combination of:
• A browser built-in XMLHttpRequest object (to request
data from a web server)
• JavaScript and HTML DOM (to display or use the data)
• AJAX applications might use XML to transport data, but
it is equally common to transport data as plain text or
JSON text.
How AJAX works?
AJAX communicates
with the server
using
XMLHttpRequest
object
As you can see in the above example, XMLHttpRequest object plays a important role.
1. User sends a request from the UI and a javascript call goes to XMLHttpRequest
object.
2. HTTP Request is sent to the server by XMLHttpRequest object.
3. Server interacts with the database using JSP, PHP, Servlet, ASP.net etc.
4. Data is retrieved.
5. Server sends XML data to the XMLHttpRequest callback function.
6. HTML and CSS data is displayed on the browser.
An object of XMLHttpRequest is used for asynchronous communication between
client and server.It performs following operations:
1. Sends data from the client in the background
2. Receives the data from the server
3. Updates the webpage without reloading it.
Interaction between client and server
through AJAX
Comparison between conventional model and
AJAX Model
Conventional model AJAX model
The browser creates a JavaScript call, which then creates
The browser sends an HTTP request to the server.
a new XMLHttpRequest object.
The new XMLHttpRequest object transfers data between
The web server receives and processes the request.
the browser and the web server in an XML format.
The XMLHttpRequest object sends a request for the
The web server sends the requested data to the updated page data to the web server. Subsequently, the
browser. latter processes the request and sends it back to the
browser.
The browser receives the data from the server and
reloads it as an HTML page.
The browser uses JavaScript to process the response and
displays the updated content directly on the HTML page
Users have to wait until it finishes loading. Therefore,
without reloading.
the conventional model increases the load on the server
and is more time-consuming.
AJAX - Send a Request To a Server
• The XMLHttpRequest object is used to exchange data with a
server.
• To send a request to a server, we use the open() and send()
methods of the XMLHttpRequest object:
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
Method Description
open(method, url, async) Specifies the type of request

method: the type of request: GET or POST


url: the server (file) location
async: true (asynchronous) or false (synchronous)
send() Sends the request to the server (used for GET)
send(string) Sends the request to the server (used for POST)
GET & POST Requests
• A simple GET request:
xhttp.open("GET", "demo_get.asp", true);
xhttp.send();
• A simple POST request:
xhttp.open("POST", "demo_post.asp", true);
xhttp.send();
• The onreadystatechange Property
• With the XMLHttpRequest object you can define a function to be executed when
the request receives an answer.
• The function is defined in the onreadystatechange property of the
XMLHttpResponse object:

xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
AJAX - Server Response

• The onreadystatechange Property Property Description


onreadystatechang Defines a function to be called when the
• The readyState property holds the e readyState property changes
status of the XMLHttpRequest. readyState Holds the status of the XMLHttpRequest.
0: request not initialized
• The onreadystatechange property 1: server connection established
2: request received
defines a function to be executed 3: processing request
when the readyState changes. 4: request finished and response is ready
status 200: "OK"
• The status property and 403: "Forbidden"
the statusText property holds the 404: "Page not found"
For a complete list go to the Http
status of the XMLHttpRequest Messages Reference
object. statusText Returns the status-text (e.g. "OK" or "Not
Found")
AJAX Example
<!DOCTYPE html>
<html>
<body>
<div id="demo">
<h2>Let AJAX change this text</h2>
<button type="button" onclick="loadDoc()">Change
Content</button>
</div>
</body>
</html>
• The HTML page contains a <div> section and a
<button>.
• The <div> section is used to display information from a
server.
• The <button> calls a function (if it is clicked).
• The function requests data from a web server and
displays it:
Function loadDoc()
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {

document.getElementById("demo").innerHTML = this.respon
seText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
<!DOCTYPE html>
<html>
<body>

<div id="demo">
<h1>The XMLHttpRequest Object</h1>
<button type="button" onclick="loadDoc()">Change Content</button>
</div>

<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
</script>

</body>
</html>
The "ajax_info.txt" file used in the example above, is a
simple text file and looks like this

<h1>AJAX</h1>
<p>AJAX is not a programming language.</p>
<p>AJAX is a technique for accessing web servers
from a web page.</p>
<p>AJAX stands for Asynchronous JavaScript And
XML.</p>
Advantages:

1. Speed is enhanced as there is no need to reload the page again.


2. AJAX make asynchronous calls to a web server, this means client
browsers avoid waiting for all the data to arrive before starting of
rendering.
3. Form validation can be done successfully through it.
4. Bandwidth utilization – It saves memory when the data is fetched from
the same page.
5. More interactive.
Disadvantages:

1. Ajax is dependent on Javascript. If there is some Javascript problem


with the browser or in the OS, Ajax will not support.
2. Ajax can be problematic in Search engines as it uses Javascript for
most of its parts.
3. Source code written in AJAX is easily human readable. There will be
some security issues in Ajax.
4. Debugging is difficult.
5. Problem with browser back button when using AJAX enabled pages.
Applications of AJAX
•Voting and rating systems – once you click a rate or vote button, the
website automatically updates the calculation without refreshing the page.
•Chat rooms – some websites implement a built-in customer support chat
room on their main page. Using AJAX, you can talk with a customer support
representative while exploring the website. The web page won’t need to
reload whenever you send or receive a new message.
•Social media – many social media applications, such as Twitter use AJAX
to update their users’ timelines. The system will request and retrieve data
from the server when you post a new tweet. Then, it will display the new
tweet on top of the timeline.
Networking
• Web Technology refers to the various tools and techniques that are utilized in the
process of communication between different types of devices over the internet. A web
browser is used to access web pages. Web browsers can be defined as programs that
display text, data, pictures, animation, and video on the Internet. Hyperlinked resources
on the World Wide Web can be accessed using software interfaces provided by Web
browsers.
• Web Technology can be classified into the following sections:
World Wide Web (WWW): The World Wide Web is based on several different
technologies : Web browsers, Hypertext Markup Language (HTML) and Hypertext
Transfer Protocol (HTTP).
• Web Browser: The web browser is an application software to explore www (World Wide
Web). It provides an interface between the server and the client and requests to the
server for web documents and services.
• Web Server: Web server is a program which processes the network requests of the users
and serves them with files that create web pages. This exchange takes place using
Hypertext Transfer Protocol (HTTP).
• Web Pages: A webpage is a digital document that is linked to the World Wide Web and
viewable by anyone connected to the internet has a web browser.
Web Development: Web development refers to the building, creating, and maintaining of websites. It
includes aspects such as web design, web publishing, web programming, and database management. It is
the creation of an application that works over the internet i.e. websites.
Web Development can be classified into two ways:
•Frontend Development: The part of a website that the user interacts directly is termed as front end. It is also
referred to as the ‘client side’ of the application.
•Backend Development: Backend is the server side of a website. It is the part of the website that users
cannot see and interact. It is the portion of software that does not come in direct contact with the users. It is
used to store and arrange data.
Below are two common data formats used in web
development.
•XML: Extensible Markup Language (XML) is a markup
language that defines a set of rules for encoding documents
in a format that is both human-readable and
machine-readable.
•JSON: JSON or JavaScript Object Notation is a format for
structuring data.
API: API is an abbreviation for Application Programming
Internet Addressing
• The Internet addressing consists of Internet Protocol (IP) addresses .
• The Internet Protocol (IP) uses a 32-bit, two-part address field.
• An IP address is a unique address that identifies a device on the internet or a local
network. IP stands for "Internet Protocol," which is the set of rules governing the
format of data sent via the internet or local network.
• IP addresses are the identifier that allows information to be sent between devices
on a network: they contain location information and make devices accessible for
communication. The internet needs a way to differentiate between different
computers, routers, and websites. IP addresses provide a way of doing so and
form an essential part of how the internet works.
• Communication at the network layer in the Internet is connectionless.
Network layer in an internetwork

20.79
What is an IP Address?
• An IP address is a string of numbers separated by periods.
• IP addresses are expressed as a set of four numbers — an
example address might be 192.158.1.38.
• Each number in the set can range from 0 to 255. So, the full IP
addressing range goes from 0.0.0.0 to 255.255.255.255.
Types of IP Address
1. IPv4: Internet Protocol version 4.
• It consists of 4 numbers separated by the dots. Each number can be from 0-255 in
decimal numbers. But computers do not understand decimal numbers, they instead
change them to binary numbers which are only 0 and 1.
• Therefore, in binary, this (0-255) range can be written as (00000000 – 11111111).
Since each number N can be represented by a group of 8-digit binary digits. So, a
whole IPv4 binary address can be represented by 32-bits of binary digits.
• In IPv4, a unique sequence of bits is assigned to a computer, so a total of (2^32)
devices approximately = 4,294,967,296 can be assigned with IPv4.
• IPv4 can be written as:
189.123.123.90
Features of IPV4
• An IPv4 address is a 32-bit address that uniquely and universally defines
the connection of a device (for example, a computer or a router) to the
Internet.
• It is a connectionless protocol.
• It utilizes less memory and the addresses can be remembered easily with
the class based addressing scheme.
• It also offers video conferencing and libraries.
• The address space of IPv4 is 232 or 4,294,967,296.
Position of IPv4 in TCP/IP protocol suite

20.83
• The packet transmitted by the sending computer may pass through several LANs
or WANs before reaching the destination computer.
• For this level of communication, we need a global addressing scheme; we called
this logical addressing
• we use the term IP address to mean a logical address in the network layer of the
TCP/IP protocol suite.
• The Internet addresses are 32 bits in length; this gives us a maximum of 2 32
addresses. These addresses are referred to as IPv4 (IP version 4) addresses or
simply IP addresses if there is no confusion.
IPv4 datagram format

20.85
The IPV4 Protocol
The IPv4 (Internet Protocol) header consists of:
• Version: which version of the protocol
• IHL: how long the header is.(5-15)
• Type of service: reliability/speed. (6-bit= 3bit precedence + 3
flags D, T, R (delay, throughput, reliability)) (ignored)
• Total length: header + data (max 65535 bytes)
• Identification: to determine which datagram a newly arrived
fragment belongs to.
• DF: don’t fragment (destination is unable to reassemble)
• MF: More fragment and all except the last one have this bit
set.
The IPV4 Protocol
The IPv4 (Internet Protocol) header consists of:
• Fragment offset: tells where in the datagram this fragment
belongs. (multiple of 8 bytes)(13 bits so max 8192 fragments
per datagram)
• Time to live: counter used to limit packet lifetime.(max 255s)
• Protocol: to which transport process to give it to.( TCP/UDP)
• Checksum: verifies the header only.
• Options: to include information not present in the original
design.
The total length field defines the total length of the datagram
including the header.

20.88
IPV4 Addresses

IP address formats.
Dotted-decimal notation and binary notation for an IPv4 address
Example

Change the following IPv4 addresses from dotted-decimal


notation to binary notation.

Solution
We replace each decimal number with its binary
equivalent.
Example

Find the error, if any, in the following IPv4 addresses.

Solution
a. There must be no leading zero (045).
b. There can be no more than four numbers.
c. Each number needs to be less than or equal to 255.
d. A mixture of binary notation and dotted-decimal
notation is not allowed.
Note

In classful addressing, the address


space is divided into five classes:
A, B, C, D, and E.
Finding the classes in binary and dotted-decimal notation
The diagram below illustrates the format of the commercial IP address classes.

The address class can be determined using the following table. For example, IP address 172.31.1.2 has a
first octet of 172, which falls between
128 and 191, so 172.31.1.2 is a Class B address.
Determining the Address Class
Class First octet High-order bits
A 1 - 126 0
B 128 - 191 10
C 192 - 223 110
D 224 - 239 1110
E 240 - 254 1111
An ip address is divided into two parts:
•Network ID: It represents the number of networks.
•Host ID: It represents the number of hosts.

Class A
In Class A, an IP address is assigned to those networks that contain a large number of hosts.M
376
•The network ID is 8 bits long.ay
•The host ID is 24 bits long.

In Class A, the first bit in higher order bits of the first octet is always set to 0 and the remaining
7 bits determine the network ID. The 24 bits determine the host ID in any network.
The total number of networks in Class A = 27 = 128 network address
The total number of hosts in Class A = 224 - 2 = 16,777,214 host address
Class B
In Class B, an IP address is assigned to those networks that range from small-sized to large-sized networks.
•The Network ID is 16 bits long.
•The Host ID is 16 bits long.
In Class B, the higher order bits of the first octet is always set to 10, and the remaining
14 bits determine the network ID. The other 16 bits determine the Host ID.
The total number of networks in Class B = 214 = 16384 network address
The total number of hosts in Class B = 216 - 2 = 65534 host address

Class C
In Class C, an IP address is assigned to only small-sized networks.
•The Network ID is 24 bits long.
•The host ID is 8 bits long.
In Class C, the higher order bits of the first octet is always set to 110, and the remaining
21 bits determine the network ID. The 8 bits of the host ID determine the host in a network.
The total number of networks = 221 = 2097152 network address
The total number of hosts = 28 - 2 = 254 host address
Class D
In Class D, an IP address is reserved for multicast addresses. It does not possess subnetting.
The higher order bits of the first octet is always set to 1110, and the remaining bits determine the host
ID in any network.

Class E
In Class E, an IP address is used for future use or for research and development purposes.
It does not possess any subnetting.
The higher-order bits of the first octet is always set to 1111, and the remaining bits determine
the host ID in any network.
Rules for assigning Host ID:
The Host ID is used to determine the host within any network. The Host ID is assigned based on the following
rules:
•The Host ID must be unique within any network.
•The Host ID in which all the bits are set to 0 cannot be assigned as it is used to represent the network ID of the
IP address.
•The Host ID in which all the bits are set to 1 cannot be assigned as it is reserved for the multicast address.

Rules for assigning Network ID:


If the hosts are located within the same local network, then they are assigned with the same network ID. The following
are the rules for assigning Network ID:
•The network ID cannot start with 127 as 127 is used by Class A.
•The Network ID in which all the bits are set to 0 cannot be assigned as it is used to specify a particular host on the
local network.
•The Network ID in which all the bits are set to 1 cannot be assigned as it is reserved for the multicast address.
IP addressing supports five address classes - A, B, C, D, and E, of which only classes A, B, and C are available
for commercial use.
The following table illustrates the IP address classes.

IP Address Classes
Class Format Purpose Address range Max hosts
A N.H.H.H A few large 1.0.0.0 - 126.0.0.0 16,777,214
organisations

B N.N.H.H Medium-size 128.1.0.0 - 65,534


organisations 191.254.0.0

C N.N.N.H Relatively small 192.0.1.0 - 254


organisations 223.255.254.0

D N/A Multicast groups 224.0.0.0 - N/A


(RFC 1112) 239.255.255.255

E N/A Experimental 240.0.0.0 - N/A


254.255.255.255
Class Higher bits NET ID bits HOST ID bits No.of No.of hosts Range
networks per network
A 0 8 24 27 224 0.0.0.0 to
127.255.255.2
55
B 10 16 16 214 216 128.0.0.0 to
191.255.255.2
55
C 110 24 8 221 28 192.0.0.0 to
223.255.255.2
55
D 1110 Not Defined Not Defined Not Defined Not Defined 224.0.0.0 to
239.255.255.2
55
E 1111 Not Defined Not Defined Not Defined Not Defined 240.0.0.0 to
255.255.255.2
55
Example

Find the class of each address.


a. 00000001 00001011 00001011 11101111
b. 11000001 10000011 00011011 11111111
c. 14.23.120.8
d. 252.5.15.111

Solution
a. The first bit is 0. This is a class A address.
b. The first 2 bits are 1; the third bit is 0. This is a class C
address.
c. The first byte is 14; the class is A.
d. The first byte is 252; the class is E.
IPv4 (disadvantages)

• Address space is inefficient.


• Audio/video need min delay. Reservation of resources not provided
in IPv4.
• No security mechanism.
IPv6
• IPv6 is the latest version of Internet protocol. It aims at fulfilling the
need of more internet addresses.
• It provides solutions for the problems present in IPv4. It provides
128-bit address space that can be used to form a network of 340
undecillion unique IP addresses.
• IPv6 is also identified with a name IPng (Internet Protocol next
generation).
Features of IPv6:
• It has a stateful and stateless both configurations.
• It provides support for quality of service (QoS).
• It has a hierarchical addressing and routing infrastructure.
IPv6 address in binary and hexadecimal colon notation

19.106
InetAddress Class in Networking

• InetAddress class is a representation of an IP address. It represents both the 32-bit


IPv4 address and the 128-bit IPv6 address. It is the superclass of Inet6Address and
Inet4Address classes.
• The InetAddress class is used to encapsulate both the numerical IP address and the
domain name for that address.
• You interact with this class by using the name of an IP host, which is more
convenient and understandable than its IP address.
• The InetAddress class hides the number inside.
• InetAddress can handle both IPv4 and IPv6 addresses.
• Java InetAddress class represents an IP address. The java.net.InetAddress
class provides methods to get the IP of any host name for
example www.javatpoint.com, www.google.com, www.facebook.com, etc.
• An IP address is represented by 32-bit or 128-bit unsigned number. An
instance of InetAddress represents the IP address with its corresponding host
name.
• There are two types of addresses: Unicast and Multicast. The Unicast is an
identifier for a single interface whereas Multicast is an identifier for a set of
interfaces.
• Moreover, InetAddress has a cache mechanism to store successful and
unsuccessful host name resolutions.
Factory methods available in InetAddress class

Method Description

public static InetAddress getLocalHost() throws This method returns the instance of InetAddress containing the
UnknownHostException local hostname and address.

public static InetAddress getByName( String host ) throws This method returns the instance of InetAddress containing IP
UnknownHostException and Host name of host represented by host argument.

public static InetAddress[] getAllByName( String hostName This method returns the array of the instance of InetAddress
) throws UnknownHostException class which contains IP addresses.

public static InetAddress getByAddress( byte IPAddress[] This method returns an InetAddress object created from the raw
) throws UnknownHostException IP address.

public static InetAddress getByAddress( String hostName, byte This method creates and returns an InetAddress based on the
IPAddress[] ) throws UnknownHostException provided hostname and IP address.
InetAddress — Instance Methods

• InetAddress class has plenty of instance methods that can be called using the object. The instance methods are

Method Description

equals(Object obj) This function compares this object against the specified object.

getAddress() This method returns the raw IP address of this InetAddress object, in bytes.

getCanonicalHostName() This method returns the fully qualified domain name for this IP address.

getHostAddress() This method gets the IP address in string form.

getHostName() This method returns the host name for this IP address.

hashCode() This method gets a hashcode for this IP address.

isAnyLocalAddress() This method utility routine to check if the InetAddress is an unpredictable address.

isLinkLocalAddress() This method utility routine to check if the address is not linked to local unicast address.
isLoopbackAddress() This method used to check if the InetAddress represents a loopback address.

This method utility routine check if this address has a multicast address of
isMCGlobal()
global scope.

This method utility routine check if this address has a multicast address of
isMCLinkLocal()
link-local scope.

isMCNodeLocal() This method utility routine check if the multicast address has node scope.

This method utility routine check if the multicast address has an organization
isMCOrgLocal()
scope.

isMCSiteLocal() This method utility routine check if the multicast address has site scope.
Packet Switching in Computer Networks
• Packet Switching is a technique of switching in which the
message is usually divided into smaller pieces that are known
as packets.

• There are two common packet switching methods in use:


• Datagram Packet Switching: Each packet is forwarded
independently based on the destination address. ...
• Virtual Circuit Packet Switching: A route is set up prior to
packets being sent.
Datagram Switching
• In Datagram Switching, the packet is commonly known as
a datagram.
• Datagram Packet switching is also known as Connectionless
Packet Switching. In this technique, each packet routed
individually by network devices on the basis of the destination
address that is contained within each packet.
Datagram Network
• In a connectionless communication systems, datagram
refers to the smallest unit via which data is transmitted.
• Datagrams are data packets which contain adequate
header information so that they can be individually
routed by all intermediate network switching devices to
the destination.
• These networks are called datagram networks since
communication occurs via datagrams. They exist in
packet switching networks.
• Each packet is basically treated independently of all others.
• Datagram packet switching is done at the network layer.
• This is Connectionless packet switching because the packet switch does not keep
the information about the connection state.
• In the Datagram packet switching the path is not fixed.
• Routing decisions are taken by the intermediate nodes in order to forward the
packets.
• Thus all datagrams that belong to the same message may travel through different
paths in order to reach their destination.
• On the receiving node, all the packets are reassembled to get the message in the
original form.
• Due to lack of resources packets may also be lost or dropped.
• In most of the protocols, it is the responsibility of the upper-layer protocol to
reorder the datagrams or to ask for the lost datagrams before passing them on to
the application.
• The following diagram shows datagram packets being
send by host H1 to host H2.
• The four datagram packets labelled as A, B, C and D, all
belonging to same message are being routed separately
via separate routes.
• The packets in the message arrives in the destination
out of order. It is the responsibility of H2 to reorder the
packets in order to retrieve the original message.
Features of Datagram Networks
• In datagram networks, each data packet or datagram is routed independently from
the source to the destination even if they belong to the same message. The
network treats the packet as if it exists alone.
• Since the datagrams are treated as independent units, no dedicated path is fixed
for data transfer.
• Each datagram is routed by the intermediate routers using dynamically changing
routing tables. So two successive packets from the source may follow completely
separate routes to reach destination.
• In these networks, no prior resource allocation is done for the individual packets.
This implies that no resources like buffers, processors, bandwidth, etc. are
reserved before the communication commences.
• In datagram networks, resources are allocated on demand on a First−Come
First−Serve (FCFS) basis. When a packet arrives at a router, the packet must wait
if there are other packets being processed, irrespective of its source or destination.
• Datagram communication is generally guided by User Datagram Protocol or UDP.
Virtual Circuit Switching
• Virtual Circuit Switching is also known as Connection-Oriented
Switching.
• This switching contains the characteristics of circuit switching as
well as datagram packet switching.
• In this type of packet switching the data-packets are first
assembled and then sequentially numbered.
• Now they are ready to travel across a predefined route,
sequentially.
• The information about the address is not required here,
because all the data packets are sent in sequence.
•Virtual Circuit Switching is also known as connection-oriented
switching.
•In the case of Virtual circuit switching, a preplanned route is
established before the messages are sent.
•Call request and call accept packets are used to establish the
connection between sender and receiver.
•In this case, the path is fixed for the duration of a logical
connection.
TCP/IP sockets
• TCP/IP sockets are used to implement reliable, bidirectional,
persistent, point-to-point, stream-based connections between
hosts on the Internet.
• A socket can be used to connect Java's I/O system to other
programs that may reside either on the local machine or on any
other machine on the Internet.
• Socket is the basis of a modern network because the socket allows one
computer to run multiple clients at the same time, as well as to provide
multiple types of information.
• And it is achieved by using a port, which is a numbered socket on a
specific machine.
•Now, until the client connects to the server, the server process
is said to "listen" to a port.
•The server is allowed to host multiple clients connected to the
same port number, although each session is different.
•In order to control multi-client connections, the server
process must be multi-threaded or have other ways of
multiplexing the simultaneous I/O.
Socket Programming in Java
• Java is a high-level language that can be used to set up connections between a server and a
client.
• The server creates the listener socket, and the client connects to it.
• For connection-oriented socket programming, the Socket class and the Server Socket class
are used.
• Sockets are important for computer networking.
• These are regarded as the endpoints of the communication line.
• Two sockets must be created at both the server and client ends to connect two machines.
• The ServerSocket class of the Java computer language controls the server end of the
socket, whereas the Server class controls the client end.
• The client must understand the characteristics of the IP address and port number in order
to connect to the server.
• After submitting a request, the client must wait for the server to authorize it. The server
approves the request using the accept() function.
• Java Socket Programming are divided into two sections.
• Client-Side Socket Program
• Server-Side Socket Program
Client-Side Socket Programming
• In client-side programming, the client will wait for the server to start
before it does anything.
• It will send the requests to the server once it is up and running.
• The client will then wait for a reply from the server. So, this is how
clients and servers talk to each other. Now, let's learn more about what
client-side programming and server-side programming are.
steps to start a client's request:
1. Initiate Connection to a Server:
• The first step is to set up a connection to a socket. A socket connection
means that the two machines know each other's location on the
network (IP Address) and TCP port.
• To make a connection to a server, create a new Socket object using one
of the following constructors:
• - Socket(InetAddress address, int port)
• - Socket(String host, int port)
• - Socket(InetAddress address, int port, InetAddress localAddr, int
localPort)
2. Communication
• Streams are used to communicate across a socket connection for both input and output
data. After establishing a connection and sending requests, the connection must be closed.
• To send data to the server, get the OutputStream object from the socket first:
• Then you can use the write() method on the OutputStream to write an array of byte to be sent:
byte[] data = ….
output.write(data);
Read Data from the Server:
InputStream input = socket.getInputStream();
Then use the read() method on the InputStream to read data as an array of byte, like this:
byte[] data =…
input.read(data);
3. Closing the connection
OutputStream output = socket.getOutputStream();
• The socket connection is explicitly closed once the message has been
transmitted to the server.
• Now let's examine how to construct a Java program to implement a
client-side socket connection.
• socket.close();
Constructor to Create TCP/IP Client Socket:
Socket(String hostName, int port) throws UnknownHostException,
IOException: Creates a socket connected to the named host and port.
Socket(InetAddress ipAddress, int port) throws IOException: Creates a
socket using a preexisting InetAddress object and a port.
Instance Methods of TCP/IP Client Socket:
InetAddress getInetAddress(): Returns the InetAddress associated with the
Socket object. It returns null if the socket is not connected.
int getPort(): Returns the remote port to which the invoking Socket object
is connected. It returns 0 if the socket is not connected.
int getLocalPort(): Returns the local port to which the invoking Socket
object is bound. It returns –1 if the socket is not bound.
I/O Stream of TCP/IP Client Socket:
InputStream getInputStream( ) throws IOException: Returns the InputStream associated with the invoking
socket.
OutputStream getOutputStream( ) throws IOException: Returns the OutputStream associated with the
invoking socket.
TCP/IP Server Socket:
Java has a different socket class that must be used for creating server applications.
The TCP/IP Server Socket class is used to create servers that listen for either local or remote client programs to
connect to them on published ports.
ServerSockets are quite different from normal Sockets.
When you create a ServerSocket, it will register itself with the system as having an interest in client connections.
The queue length tells the system how many
client connections it can leave pending before it should simply refuse connections. The default is 50.
Constructor to Create TCP/IP Server Socket:
ServerSocket(int port) throws IOException: Creates server socket on the specified port with a queue length of
50.
ServerSocket(int port, int maxQueue) throws IOException: Creates a server socket on the specified port with a
maximum queue length of the max queue.
ServerSocket(int port, int maxQueue, InetAddress local address) throws IOException: Creates a server socket
on the specified port with a maximum queue length
of the max queue. On a multihomed host, the local address specifies the IP address to which this socket binds.
URL
• URL is an abbreviation for Uniform Resource Locator. An URL is a
form of string that helps to find a resource on the World Wide Web
(WWW).
• URL has two components:
1. The protocol required to access the resource.
2. The location of the resource.
Features of URLConnection class
1. 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.
2. With the help of URLConnection class, a user can read and write to
and from any resource referenced by an URL object.
3. Once a connection is established and the Java program has an
URLConnection object, we can use it to read or write or get further
information like content length, etc.
URLConnection:
It is a general-purpose class for accessing the attributes of a remote resource. Once you make a
connection to a remote server, you can use URLConnection to inspect the properties of the
remote object before actually transporting it locally.
These attributes are exposed by the HTTP protocol specification and, as such, only make sense for
URL objects that are using the HTTP protocol.
URLConnection Methods:
int getContentLength(): Returns the size in bytes of the content associated with the resource.
If the length is unavailable, –1 is returned.
String getContentType(): Returns the type of content found in the resource. This is the value of
the content-type header field.
long getDate(): Returns the time and date of the response represented in terms of milliseconds.
long getExpiration(): Returns the expiration time and date of the resource represented in terms of
milliseconds
String getHeaderField(int idx): Returns the value of the header field at index idx.
Returns null if the value of idx exceeds the number of fields.
String getHeaderField(String fieldName): Returns the value of header field whose name is
specified by fieldName.
Returns null if the specified name is not found.
String getHeaderFieldKey(int idx): Returns the header field key at index idx. Returns
null if the value of idx exceeds the number of fields.
Map<String, List<String>> getHeaderFields(): Returns a map that contains all of the
header fields and values.

long getLastModified(): Returns the time and date, represented in terms of


milliseconds.
InputStream getInputStream() throws IOException: Returns an InputStream that is
linked to the resource.
This stream can be used to obtain the content of the resource.

You might also like