0% found this document useful (0 votes)
53 views52 pages

Unit-3 Javascript

unit-3 javascript
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
53 views52 pages

Unit-3 Javascript

unit-3 javascript
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 52

Unit-3 JavaScript & Networking

Lecture No Topic Description


19 Scripting: Java script: Introduction, documents, forms
20 statements, functions
21 objects, introduction to AJAX
22 Networking: Internet Addressing, InetAddress
23 Factory Methods, Instance Methods
24 TCP/IP Client Sockets
25 URL, URL Connection
26 TCP/IP Server Sockets, Datagram

Lecture 19:
3.1 JAVASCRIPT: INTRODUCTION

It is used to Add interactivity to web pages.


3.1.1 What is JavaScript?
JavaScript is a scripting language that allows developers to create dynamic and interactive web pages. It
enables browsers to respond to user interactions and change the content layout of a webpage.
3.1.2 Why use JavaScript?
JavaScript is a tool for developers to add interactivity to websites.
JavaScript is a light-weight object-oriented programming language that is used by several websites for
scripting the webpages. It is an interpreted, full-fledged programming language. JavaScript enables
dynamic interactivity on websites when it is applied to an HTML document.
JavaScript helps the users to build modern web applications to interact directly without reloading the
page every time. JavaScript is commonly used to dynamically modify HTML and CSS to update a user
interface by the DOM API. It is mainly used in web applications.
3.1.3 Where to Use javaScript?
JavaScript is a programming language used to create dynamic content for websites. uses of JavaScript
are following:
1. Web Development
2. Web Applications

1
3. Front-End Development
4. Server Applications
5. Back-End Development
6. Web Servers
7. Games
8. Art
9. Smartwatch Apps
10. Mobile Apps

11. Data Visualization

12. API Development

3.1.4 Features of JavaScript


There are following 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 weekly 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.
3.1.5 History of JavaScript
In 1993, Mosaic, the first popular web browser, came into existence. In the year 1994, Netscape was
founded by Marc Andreessen. He realized that the web needed to become more dynamic. Thus, a 'glue
language' was believed to be provided to HTML to make web designing easy for designers and part-time
programmers. Consequently, in 1995, the company recruited Brendan Eich intending to implement and
embed Scheme programming language to the browser. But, before Brendan could start, the company
merged with Sun Microsystems for adding Java into its Navigator so that it could compete with
Microsoft over the web technologies and platforms. Now, two languages were there: Java and the
2
scripting language. Further, Netscape decided to give a similar name to the scripting language as Java's.
It led to 'Javascript'. Finally, in May 1995, Marc Andreessen coined the first code of Javascript named
'Mocha'. Later, the marketing team replaced the name with 'LiveScript'. But, due to trademark reasons
and certain other reasons, in December 1995, the language was finally renamed to 'JavaScript'. From
then, JavaScript came into existence.

3.1.6 Application of JavaScript

JavaScript is used to create interactive websites. It is mainly used for:


o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box and
prompt dialog box),
o Displaying clocks etc.

3.1.7 How to use javaScript?

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>
Example:
<!DOCTYPE html>
<html lang="en">

<head>

3
<title>
Basic Example to Describe JavaScript
</title>
</head>

<body>

<!-- JavaScript code can be embedded inside


head section or body section -->
<script>
console.log("Welcome to JavaScript");
</script>
</body>

</html>
Output: The output will display on the console.
Welcome to JavaScript
3.2 JAVASCRIPT DOCUMENT

3.2.1 What is a JavaScript document?

A document is an object in JavaScript that gives access and manipulates the HTML document loaded. It
is the root node of the document and provides an interface for manipulation of the document structure.

3.2.2 Why and Where to use document?

When we want to write some string on web page then we use document.

Syntax of JavaScript Document.write()

document.write(expression_1, expression_2, expression_3.....expression_n)

Example-

4
<!DOCTYPE html>
<html>
<head>
<title>Hello, World!</title>
</head>
<body>
<script type="text/javascript">
document.write("hello everyone");
</script>

</body>
</html>

Output: hello everyone

3.2.3 The Document Object

When an HTML document is loaded into a web browser, it becomes a document object.
The document object is the root node of the HTML document.
The document object is a property of the window object.
The document object is accessed with:
Examples
1.Write some text directly to the HTML output:
document.write("Hello World!");
2.Write some HTML elements directly to the HTML output:
document.write("<h2>Hello World!</h2><p>Have a nice day!</p>");
3.Write a date object directly to the HTML ouput:
document.write(Date());

3.3 JAVASCRIPT FORM

3.3.1 What is a JavaScript form?

5
In JavaScript a form is an HTML element used to collect user input. Forms consist of one or more input
elements and a submit button used to submit the form's data to a web server.

3.3.2 Why use HTML Form?

HTML forms are required if you want to collect some data from of the site visitor.
For example: If a user want to purchase some items on internet, he/she must fill the form such as
shipping address and credit/debit card details so that item can be sent to the given address.

3.3.3 How to use HTML Form?

Add form tag in HTML body to generate HTML form.


HTML Form Syntax
<form action="server url" method="get|post">
//input controls e.g. textfield, textarea, radiobutton, button
</form>

3.3.4 JavaScript Form Validation

HTML form validation can be done by JavaScript.


If a form field (fname) is empty, this function alerts a message, and returns false, to prevent the form
from being submitted:
JavaScript Example
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
alert("Name must be filled out");
return false;
}
}
The function can be called when the form is submitted:
HTML Form Example

6
<form name="myForm" action="/action_page.php" onsubmit="return
validateForm()" method="post">
Name: <input type="text" name="fname">
<input type="submit" value="Submit">
</form>
Lecture 20
3.4 STATEMENTS
3.4.1 JavaScript Statements
There are many different types of statements available in JavaScript, including variable declarations,
assignment statements, arithmetic statements, conditional statements, loop statements, and jump
statements. Variable declarations are used to create variables in JavaScript.
JavaScript Variable
var x = 10;
var _value="sonoo";
Example-
<script>
var x = 10;
var y = 20;
var z=x+y;
document.write(z);
</script>
3.4.1.1 JavaScript primitive data types
There are five types of primitive data types in JavaScript. They are as follows:

Data Type Description

String represents sequence of characters e.g. "hello"

Number represents numeric values e.g. 100

Boolean represents boolean value either false or true

Undefined represents undefined value

7
Null represents null i.e. no value at all

3.4.1.2 JavaScript Operators


There are following types of operators in JavaScript.
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators

Figure 3.1 Operators


3.4.2 Conditional Statements
Conditional statements are used to perform different actions based on different conditions.
Very often when you write code, you want to perform different actions for different decisions.
You can use conditional statements in your code to do this.
In JavaScript we have the following conditional statements:
● Use if to specify a block of code to be executed, if a specified condition is true
● Use else to specify a block of code to be executed, if the same condition is false

8
● Use else if to specify a new condition to test, if the first condition is false
● Use switch to specify many alternative blocks of code to be executed

3.4.2.1 The if Statement

Use the if statement to specify a block of JavaScript code to be executed if a condition is true.
Syntax
if (condition) {
// block of code to be executed if the condition is true
}
Example
Make a "Good day" greeting if the hour is less than 18:00:
if (hour < 18) {
greeting = "Good day";
}
The result of greeting will be:
Good day

3.4.2.2 The else Statement

Use the else statement to specify a block of code to be executed if the condition is false.
if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
Example
If the hour is less than 18, create a "Good day" greeting, otherwise "Good evening":
if (hour < 18) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
9
The result of greeting will be:
Good day

3.4.2.3 The else if Statement

Use the else if statement to specify a new condition if the first condition is false.
Syntax
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}
Example
If time is less than 10:00, create a "Good morning" greeting, if not, but time is less than 20:00, create a
"Good day" greeting, otherwise a "Good evening":
if (time < 10) {
greeting = "Good morning";
} else if (time < 20) {
greeting = "Good day";
} else {
greeting = "Good evening";
}
The result of greeting will be:
Good day
3.4.2.4 JavaScript Switch Statement

The JavaScript Switch Statement

Use the switch statement to select one of many code blocks to be executed.
Syntax
switch(expression) {
10
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This is how it works:
● The switch expression is evaluated once.
● The value of the expression is compared with the values of each case.
● If there is a match, the associated block of code is executed.
● If there is no match, the default code block is executed.
Example
The getDay() method returns the weekday as a number between 0 and 6.
(Sunday=0, Monday=1, Tuesday=2 ..)
This example uses the weekday number to calculate the weekday name:
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
11
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
}
The result of day will be:
Monday
3.4.2.5 JavaScript Break and Continue
The break statement "jumps out" of a loop.
The continue statement "jumps over" one iteration in the loop.

The Break Statement

You have already seen the break statement used in an earlier chapter of this tutorial. It was used to
"jump out" of a switch() statement.
The break statement can also be used to jump out of a loop:
Example
for (let i = 0; i < 10; i++) {
if (i === 3) { break; }
text += "The number is " + i + "<br>";
}
In the example above, the break statement ends the loop ("breaks" the loop) when the loop counter (i) is
3.

3.4.2.6 The Continue Statement

The continue statement breaks one iteration (in the loop), if a specified condition occurs, and continues
with the next iteration in the loop.
This example skips the value of 3:
Example
12
for (let i = 0; i < 10; i++) {
if (i === 3) { continue; }
text += "The number is " + i + "<br>";
}

3.5 JAVASCRIPT FUNCTIONS


3.5.1 What is Function?
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).
Example
// Function to compute the product of p1 and p2
function myFunction(p1, p2) {
return p1 * p2;
}
3.5.2 Why Functions?
With functions you can reuse code
You can write code that can be used many times.
You can use the same code with different arguments, to produce different results.

3.5.3 JavaScript Function Syntax


A JavaScript function is defined with the function keyword, followed by a name, followed by
parentheses ().
Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).
The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...)
The code to be executed, by the function, is placed inside curly brackets: {}
function name(parameter1, parameter2, parameter3) {
// code to be executed
}
Function parameters are listed inside the parentheses () in the function definition.
Function arguments are the values received by the function when it is invoked.

13
Inside the function, the arguments (the parameters) behave as local variables.

3.5.4 Function Return

When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the code after the
invoking statement.
Functions often compute a return value. The return value is "returned" back to the "caller":
Example
Calculate the product of two numbers, and return the result:
// Function is called, the return value will end up in x
let x = myFunction(4, 3);

function myFunction(a, b) {
// Function returns the product of a and b
return a * b;
}

3.5.5 Local Variables

Variables declared within a JavaScript function, become LOCAL to the function.


Local variables can only be accessed from within the function.
Example

// code here can NOT use carName

function myFunction() {
let carName = "Volvo";
// code here CAN use carName
}

3.5.6 Global JavaScript Variables

A variable declared outside a function, becomes GLOBAL.


14
Example
let carName = "Volvo";
// code here can use carName

function myFunction() {
// code here can also use carName
}
3.5.7 Function Parameters and Arguments
Earlier in this tutorial, you learned that functions can have parameters:
function functionName(parameter1, parameter2, parameter3) {
// code to be executed
}

3.5.8 Default Parameter Values

ES6 allows function parameters to have default values.


Example
If y is not passed or undefined, then y = 10.
function myFunction(x, y = 10) {
return x + y;
}
myFunction(5);
Lecture 21
3.6 JAVASCRIPT OBJECTS
3.6.1 What Are Objects in JavaScript?
JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method). For example: car,
pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is an object-based language. Everything is an object in JavaScript.
JavaScript is template based not class based. Here, we don't create class to get the object. But, we direct
create objects.

15
3.6.1.1 Real Life Objects
In real life, objects are things like: houses, cars, people, animals, or any other subjects.
Here is a car object example:

Car Object Properties Methods

car.name = Fiat car.start()

car.model = 500 car.drive()

car.weight = 850kg car.brake()

car.color = white car.stop()

Figure 3.2 Object


3.6.1.2 Object Properties
A real life car has properties like weight and color:
car.name = Fiat, car.model = 500, car.weight = 850kg, car.color = white.
Car objects have the same properties, but the values differ from car to car.
3.6.1.3 Object Methods
A real life car has methods like start and stop:
car.start(), car.drive(), car.brake(), car.stop().
Car objects have the same methods, but the methods are performed at different times.

3.6.1.4 Creating a JavaScript Object

These examples create a JavaScript object with 4 properties:


Examples
// Create an Object
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

3.6.1.5 Using the new Keyword

16
This example create a new JavaScript object using new Object(), and then adds 4 properties:
Example
// Create an Object
const person = new Object();

// Add Properties
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";

3.6.1.6 Accessing Object Properties

You can access object properties in two ways:


objectName.propertyName
objectName["propertyName"]
Examples
person.lastName;

3.6.1.7 JavaScript Object Methods

Methods are actions that can be performed on objects.


Methods are function definitions stored as property values.
Example
const person = {
firstName: "John",
lastName : "Doe",
id : 5566,
fullName : function() {
return this.firstName + " " + this.lastName;
}
};
In the example above, this refers to the person object:
17
this.firstName means the firstName property of person.
this.lastName means the lastName property of person.
In JavaScript, almost "everything" is an object.
● Objects are objects
● Maths are objects
● Functions are objects
● Dates are objects
● Arrays are objects
● Maps are objects
● Sets are objects
All JavaScript values, except primitives, are objects.
3.6.2 JavaScript Array
JavaScript array is an object that represents a collection of similar type of elements.
There are 3 ways to construct array in JavaScript
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
1) JavaScript array literal
The syntax of creating array using array literal is given below:
var arrayname=[value1,value2.....valueN];
As you can see, values are contained inside [ ] and separated by , (comma).
Let's see the simple example of creating and using array in JavaScript.
<script>
var emp=["Sonoo","Vimal","Ratan"];
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br/>");
}
</script>
2) JavaScript Array directly (new keyword)
The syntax of creating array directly is given below:
var arrayname=new Array();
Here, new keyword is used to create instance of array.
18
Let's see the example of creating array directly.
<script>
var i;
var emp = new Array();
emp[0] = "Arun";
emp[1] = "Varun";
emp[2] = "John";

for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
3) JavaScript array constructor (new keyword)
Here, you need to create instance of array by passing arguments in constructor so that we don't have to
provide value explicitly.
The example of creating object by array constructor is given below.
<script>
var emp=new Array("Jai","Vijay","Smith");
for (i=0;i<emp.length;i++){
document.write(emp[i] + "<br>");
}
</script>
JavaScript String
The JavaScript string is an object that represents a sequence of characters.
There are 2 ways to create string in JavaScript
1)By string literal
By string object (using new keyword)
<script>
var str="This is string literal";
document.write(str);
</script>
2) By string object (using new keyword)
19
The syntax of creating string object using new keyword is given below:
var stringname=new String("string literal");
Here, new keyword is used to create instance of string.
Let's see the example of creating string in JavaScript by new keyword.
<script>
var stringname=new String("hello javascript string");
document.write(stringname);
</script>

Methods Description

It provides the char value present at the specified


charAt()
index.

It provides the Unicode value of a character present at


charCodeAt()
the specified index.

concat() It provides a combination of two or more strings.

It provides the position of a char value present in the


indexOf()
given string.

It provides the position of a char value present in the


lastIndexOf() given string by searching a character from the last
position.

It searches a specified regular expression in a given


search()
string and returns its position if a match occurs.

It searches a specified regular expression in a given


match() string and returns that regular expression if a match
occurs.

It replaces a given string with the specified


replace()
replacement.

20
It is used to fetch the part of the given string on the
substr()
basis of the specified starting position and length.

It is used to fetch the part of the given string on the


substring()
basis of the specified index.

It is used to fetch the part of the given string. It allows


slice()
us to assign positive as well negative index.

toLowerCase() It converts the given string into lowercase letter.

It converts the given string into lowercase letter on the


toLocaleLowerCase()
basis of host?s current locale.

toUpperCase() It converts the given string into uppercase letter.

It converts the given string into uppercase letter on the


toLocaleUpperCase()
basis of host?s current locale.

toString() It provides a string representing the particular object.

valueOf() It provides the primitive value of string object.

It splits a string into substring array, then returns that


split()
newly created array.

It trims the white space from the left and right side of
trim()
the string.

3.6.2.3 JavaScript Date Object


The JavaScript date object can be used to get year, month and day. You can display a timer on the
webpage by the help of JavaScript date object.
You can use different Date constructors to create date object. It provides methods to get and set day,
month, year, hour, minute and seconds.
Let's see the simple example to print date object. It prints date and time both.
Current Date and Time: <span id="txt"></span>
21
<script>
var today=new Date();
document.getElementById('txt').innerHTML=today;
</script>
Let's see another code to print date/month/year.
<script>
var date=new Date();
var day=date.getDate();
var month=date.getMonth()+1;
var year=date.getFullYear();
document.write("<br>Date is: "+day+"/"+month+"/"+year);
</script>
JavaScript Current Time Example
Let's see the simple example to print current time of system.
Current Time: <span id="txt"></span>
<script>
var today=new Date();
var h=today.getHours();
var m=today.getMinutes();
var s=today.getSeconds();
document.getElementById('txt').innerHTML=h+":"+m+":"+s;
</script>
3.6.4 JavaScript Math
The JavaScript math object provides several constants and methods to perform mathematical
operation. Unlike date object, it doesn't have constructors.
Math.sqrt(n)
The JavaScript math.sqrt(n) method returns the square root of the given number.
Square Root of 17 is: <span id="p1"></span>
<script>
document.getElementById('p1').innerHTML=Math.sqrt(17);
</script>

22
3.6.5 JavaScript Number Object
The JavaScript number object enables you to represent a numeric value. It may be integer or floating-
point. JavaScript number object follows IEEE standard to represent the floating-point numbers.
By the help of Number() constructor, you can create number object in JavaScript. For example:
var n=new Number(value);
If value can't be converted to number, it returns NaN(Not a Number) that can be checked by isNaN()
method.
var x=102;//integer value
var y=102.7;//floating point value
var z=13e4;//exponent value, output: 130000
var n=new Number(16);//integer value by number object
3.6.5.1 JavaScript Number Constants
Let's see the list of JavaScript number constants with description.
3.6.6 JavaScript Boolean
JavaScript Boolean is an object that represents value in two states: true or false. You can create the
JavaScript Boolean object by Boolean() constructor as given below.
Boolean b=new Boolean(value);
The default value of JavaScript Boolean object is false.

JavaScript Boolean Example

<script>
document.write(10<20);//true
document.write(10<5);//false
</script>

3.7 INTRODUCTION TO AJAX


AJAX tutorial covers concepts and examples of AJAX technology for beginners and professionals.
AJAX is an acronym for Asynchronous JavaScript and XML. It is a group of inter-related
technologies like JavaScript, DOM, XML, HTML/XHTML, CSS, XMLHttpRequest etc.
3.7.1 What is AJAX?
AJAX allows you to send and receive data asynchronously without reloading the web page. So it is fast.

23
AJAX allows you to send only important information to the server not the entire page. So only valuable
data from the client side is routed to the server side. It makes your application interactive and faster.
3.7.2 Where it is used?
There are too many web applications running on the web that are using ajax technology
like gmail, facebook,twitter, google map, youtube etc.
Understanding Synchronous vs Asynchronous
Before understanding AJAX, let’s understand classic web application model and ajax web application
model first.

3.7.2.1 Synchronous (Classic Web-Application Model)

A synchronous request blocks the client until operation completes i.e. browser is unresponsive. In such
case, javascript engine of the browser is blocked.

Figure 3.3 Synchronous Model


As you can see in the above image, full page is refreshed at request time and user is blocked until
request completes.

24
Figure 3.4 Synchronous communication
3.7.2.2 Asynchronous (AJAX Web-Application Model)
An asynchronous request doesn’t block the client i.e. browser is responsive. At that time, user can
perform another operations also. In such case, javascript engine of the browser is not blocked.

Figure 3.5 ASynchronous Model


As you can see in the above image, full page is not refreshed at request time and user gets response from
the ajax engine.
Let's try to understand asynchronous communication by the image given below.

25
Figure 3.6 ASynchronous Communication
3.7.3 AJAX Technologies
As describe earlier, ajax is not a technology but group of inter-related technologies. AJAX technologies
includes:
● HTML/XHTML and CSS
● DOM
● XML or JSON
● XMLHttpRequest
● JavaScript
3.7.4 Understanding XMLHttpRequest
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.
3.7.5 How AJAX works?
AJAX communicates with the server using XMLHttpRequest object. Let's try to understand the flow of
ajax or how ajax works by the image displayed below.

26
Figure 3.7 AJAX
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 or JSON data to the XMLHttpRequest callback function.
6. HTML and CSS data is displayed on the browser.
Lecture 22
3.8 JAVA NETWORKING
3.8.1 What is Java Networking?
Java Networking is a concept of connecting two or more computing devices together so that we can
share resources.
Java socket programming provides facility to share data between different computing devices.
3.8.2 Advantage of Java Networking
1. Sharing resources
2. Centralize software management
27
The java.net package supports two protocols,
1. TCP: Transmission Control Protocol provides reliable communication between the sender and
receiver. TCP is used along with the Internet Protocol referred as TCP/IP.
2. UDP: User Datagram Protocol provides a connection-less protocol service by allowing packet of
data to be transferred along two or more nodes
3.8.3 Java Networking Terminology
The widely used Java networking terminologies are given below:
1. IP Address
2. Protocol
3. Port Number
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket
1) IP Address
IP address is a unique number assigned to a node of a network e.g. 192.168.0.1 . It is composed of octets
that range from 0 to 255.
It is a logical address that can be changed.
2) Protocol
A protocol is a set of rules basically that is followed for communication. For example:
o TCP
o FTP
o Telnet
o SMTP
o POP etc.

3) Port Number
The port number is used to uniquely identify different applications. It acts as a communication endpoint
between applications.
The port number is associated with the IP address for communication between two applications.
4) MAC Address
MAC (Media Access Control) address is a unique identifier of NIC (Network Interface Controller). A
network node can have multiple NIC but each with unique MAC address.

28
For example, an ethernet card may have a MAC address of 00:0d:83::b1:c0:8e.
5) Connection-oriented and connection-less protocol
In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable but slow. The
example of connection-oriented protocol is TCP.
But, in connection-less protocol, acknowledgement is not sent by the receiver. So it is not reliable but
fast. The example of connection-less protocol is UDP.
6) Socket
A socket is an endpoint between two way communications.

3.8.4 java.net package

The java.net package can be divided into two sections:


1. A Low-Level API: It deals with the abstractions of addresses i.e. networking identifiers, Sockets
i.e. bidirectional data communication mechanism and Interfaces i.e. network interfaces.
2. A High Level API: It deals with the abstraction of URIs i.e. Universal Resource Identifier,
URLs i.e. Universal Resource Locator, and Connections i.e. connections to the resource pointed
by URLs.
The java.net package provides many classes to deal with networking applications in Java.
3.9 INTERNET ADDRESSING
3.9.1 What is meant by internet addressing?

IP Address Definition and Explanation. An Internet Protocol (IP) address is the unique identifying
number assigned to every device connected to the internet. An IP address definition is a numeric label
assigned to devices that use the internet to communicate.
3.9.1.1 How does an IP address work?
An IP address works in helping your device, whatever you are accessing the internet on, to find whatever
data or content is located to allow for retrieval.
Common tasks for an IP address include both the identification of a host or a network, or identifying the
location of a device. An IP address is not random. The creation of an IP address has the basis of math. The
Internet Assigned Numbers Authority (IANA) allocates the IP address and its creation. The full range of IP
addresses can go from 0.0.0.0 to 255.255.255.255.

29
With the mathematical assignment of an IP address, the unique identification to make a connection to a
destination can be made.
3.9.1.1.1 Classful Addressing
The 32-bit IP address is divided into five sub-classes. These are given below:
● Class A
● Class B
● Class C
● Class D
● Class E

Figure 3.8 IP Class

Figure 3.9 Range of IP Class


3.10 INETADDRESS
3.10.1 What is InetAddress class?
30
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.

IP Address

o An IP address helps to identify a specific resource on the network using a numerical


representation.

3.10.2 Java InetAddress Class Methods

Method Description

public static InetAddress getByName(String It returns the instance of InetAddress containing


host) throws UnknownHostException LocalHost IP and name.

public static InetAddress getLocalHost() It returns the instance of InetAdddress


throws UnknownHostException containing local host name and address.

public String getHostName() It returns the host name of the IP address.

public String getHostAddress() It returns the IP address in string format.

Example of Java InetAddress Class


Let's see a simple example of InetAddress class to get ip address of www.javatpoint.com website.
InetDemo.java
import java.io.*;
import java.net.*;
public class InetDemo{
public static void main(String[] args){
31
try{
InetAddress ip=InetAddress.getByName("www.javatpoint.com");

System.out.println("Host Name: "+ip.getHostName());


System.out.println("IP Address: "+ip.getHostAddress());
}catch(Exception e){System.out.println(e);}
}
}
1. Output:

2. Host Name: www.javatpoint.com


3. IP Address: 172.67.196.82

Program to demonstrate methods of InetAddress class


InetDemo2.java
import java.net.Inet4Address;
import java.util.Arrays;
import java.net.InetAddress;
public class InetDemo2
{
public static void main(String[] arg) throws Exception
{
InetAddress ip = Inet4Address.getByName("www.javatpoint.com");
InetAddress ip1[] = InetAddress.getAllByName("www.javatpoint.com");
byte addr[]={72, 3, 2, 12};
System.out.println("ip : "+ip);
System.out.print("\nip1 : "+ip1);
InetAddress ip2 = InetAddress.getByAddress(addr);
System.out.print("\nip2 : "+ip2);
System.out.print("\nAddress : " +Arrays.toString(ip.getAddress()));
System.out.print("\nHost Address : " +ip.getHostAddress());
System.out.print("\nisAnyLocalAddress : " +ip.isAnyLocalAddress());
32
System.out.print("\nisLinkLocalAddress : " +ip.isLinkLocalAddress());
System.out.print("\nisLoopbackAddress : " +ip.isLoopbackAddress());
System.out.print("\nisMCGlobal : " +ip.isMCGlobal());
System.out.print("\nisMCLinkLocal : " +ip.isMCLinkLocal());
System.out.print("\nisMCNodeLocal : " +ip.isMCNodeLocal());
System.out.print("\nisMCOrgLocal : " +ip.isMCOrgLocal());
System.out.print("\nisMCSiteLocal : " +ip.isMCSiteLocal());
System.out.print("\nisMulticastAddress : " +ip.isMulticastAddress());
System.out.print("\nisSiteLocalAddress : " +ip.isSiteLocalAddress());
System.out.print("\nhashCode : " +ip.hashCode());
System.out.print("\n Is ip1 == ip2 : " +ip.equals(ip2));
}
}
Output:

Figure 3.10 Inet address


In the above Java code, the various boolean methods of InetAdress class are demonstrated.
Lecture 23
3.11 FACTORY METHODS

33
The InetAddress class has no visible constructors. To create an InetAddress object, you have to use one
of the available factory methods. Factory methods are merely a convention whereby static methods in a
class return an instance of that class. This is done in lieu of overloading a constructor with various
parameter lists when having unique method names makes the results much clearer. Three commonly
used InetAddress factory methods are shown here:
static InetAddress getLocalHost( ) throws UnknownHostException
static InetAddress getByName(String hostName) throws UnknownHostException
static InetAddress[ ] getAllByName(String hostName) throws UnknownHostException
The getLocalHost( ) method simply returns the InetAddress object that represents the local host. The
getByName( ) method returns an InetAddress for a host name passed to it. If these methods are unable to
resolve the host name, they throw an UnknownHostException.
On the Internet, it is common for a single name to be used to represent several machines. In the world of
web servers, this is one way to provide some degree of scaling. The getAllByName( ) factory method
returns an array of InetAddresses that represent all of the addresses that a particular name resolves to. It
will also throw an UnknownHostException if it can’t resolve the name to at least one address.
InetAddress also includes the factory method getByAddress( ), which takes an IP address and returns an
InetAddress object. Either an IPv4 or an IPv6 address can be used.
The following example prints the addresses and names of the local machine and two Internet web sites:
// Demonstrate InetAddress.
import java.net.*;
class InetAddressTest
{
public static void main(String args[]) throws UnknownHostException {
InetAddress Address = InetAddress.getLocalHost();
System.out.println(Address);
Address = InetAddress.getByName("www.HerbSchildt.com");
System.out.println(Address);
InetAddress SW[] = InetAddress.getAllByName("www.nba.com");
for (int i=0; i<SW.length; i++)
System.out.println(SW[i]);
}
}
34
Here is the output produced by this program. (Of course, the output you see may be
slightly different.)
default/166.203.115.212
www.HerbSchildt.com/216.92.65.4
www.nba.com/216.66.31.161
www.nba.com/216.66.31.179
3.12 INSTANCE METHODS
The InetAddress class has several other methods, which can be used on the objects returned by the
methods just discussed. Here are some of the more commonly used methods:

Figure 3.11 Instance Methods


Lecture 24
3.13 TCP/IP CLIENT 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.
There are two kinds of TCP sockets in Java. One is for servers, and the other is for clients. The
ServerSocket class is designed to be a "listener," which waits for clients to connect before doing
anything. Thus, ServerSocket is for servers. The Socket class is for clients. It is designed to connect to
server sockets and initiate protocol exchanges. Because client sockets are the most commonly used by
Java applications, they are examined here.
3.13.1 Java Socket Programming

35
Java Socket programming is used for communication between the applications running on different JRE.
Java Socket programming can be connection-oriented or connection-less.
Socket and ServerSocket classes are used for connection-oriented socket programming and
DatagramSocket and DatagramPacket classes are used for connection-less socket programming.
The client in socket programming must know two information:
1. IP Address of Server, and
2. Port number.
Here, we are going to make one-way client and server communication. In this application, client sends a
message to the server, server reads the message and prints it. Here, two classes are being used: Socket
and ServerSocket. The Socket class is used to communicate client and server. Through this class, we can
read and write message. The ServerSocket class is used at server-side. The accept() method of
ServerSocket class blocks the console until the client is connected. After the successful connection of
client, it returns the instance of Socket at server-side.

Figure 3.12 Socket

3.13.2 Socket class

A socket is simply an endpoint for communications between the machines. The Socket class can be used
to create a socket.

36
Important methods

Method Description

returns the InputStream


1) public InputStream getInputStream()
attached with this socket.

returns the OutputStream


2) public OutputStream getOutputStream()
attached with this socket.

3) public synchronized void close() closes this socket

3.13.3 ServerSocket class

The ServerSocket class can be used to create a server socket. This object is used to establish
communication with the clients.
Important methods

Method Description

returns the socket and


1) public Socket accept() establish a connection
between server and client.

2) public synchronized void close() closes the server socket.

Example of Java Socket Programming


Creating Server:
To create the server application, we need to create the instance of ServerSocket class. Here, we are using
6666 port number for the communication between the client and server. You may also choose any other
port number. The accept() method waits for the client. If clients connects with the given port number, it
returns an instance of Socket.
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection and waits for the client
Creating Client:

37
To create the client application, we need to create the instance of Socket class. Here, we need to pass the
IP address or hostname of the Server and a port number. Here, we are using "localhost" because our
server is running on same system.
Socket s=new Socket("localhost",6666);
Let's see a simple of Java socket programming where client sends a text and server receives and prints it.
File: MyServer.java
import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}
File: MyClient.java
import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
38
}catch(Exception e){System.out.println(e);}
}
}

Figure 3.13 Client server chatting


Lecture 25
3.14 JAVA URL

3.14.1 What is Java URL?


The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator. It points to
a resource on the World Wide Web. For example:
https://www.javatpoint.com/java-tutorial

39
A URL contains many information:
1. Protocol: In this case, http is the protocol.
2. Server name or IP Address: In this case, www.javatpoint.com is the server name.
3. Port Number: It is an optional attribute. If we write http//ww.javatpoint.com:80/sonoojaiswal/ ,
80 is the port number. If port number is not mentioned in the URL, it returns -1.
4. File Name or directory name: In this case, index.jsp is the file name.
URL(String protocol, String host, int port, String file)
Creates an instance of a URL from the given protocol, host, port number, and file.
URL(String protocol, String host, int port, String file, URLStreamHandler handler)
Creates an instance of a URL from the given protocol, host, port number, file, and handler.
URL(String protocol, String host, String file)
Creates an instance of a URL from the given protocol name, host name, and file name.

Method Description

public String getProtocol() it returns the protocol of the URL.

public String getHost() it returns the host name of the URL.

public String getPort() it returns the Port Number of the URL.

public String getFile() it returns the file name of the URL.

public String getAuthority() it returns the authority of the URL.

public String toString() it returns the string representation of the URL.

public String getQuery() it returns the query string of the URL.

public String getDefaultPort() it returns the default port of the URL.

public URLConnection it returns the instance of URLConnection i.e. associated with


openConnection() this URL.

public boolean equals(Object obj) it compares the URL with the given object.

40
public Object getContent() it returns the content of the URL.

public String getRef() it returns the anchor or reference of the URL.

public URI toURI() it returns a URI of the URL

Example of Java URL class


//URLDemo.java
import java.net.*;
public class URLDemo{
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");

System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("File Name: "+url.getFile());

}catch(Exception e){System.out.println(e);}
}
}
ouput:

Protocol: http
Host Name: www.javatpoint.com
Port Number: -1
File Name: /java-tutorial

3.15 JAVA URL CONNECTION CLASS


3.15.1 What is URL Connection?
The Java URLConnection class represents a communication link between the URL and the application.
It can be used to read and write data to the specified resource referred by the URL.
41
3.15.1.1 What is the URL?
o 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).
o URL has two components:

1. The protocol required to access the resource.


2. The location of the resource.
3.15.1.2 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.
Constructors

Constructor Description

It constructs a URL connection to the


1) protected URLConnection(URL url)
specified URL.

URLConnection Class Methods

Method Description

It adds a general request property specified by


void addRequestProperty(String key, String value)
a key-value pair

It opens a communications link to the


void connect() resource referenced by this URL, if such a
connection has not already been established.

It returns the value of the


boolean getAllowUserInteraction()
allowUserInteraction field for the object.

42
int getConnectionTimeout() It returns setting for connect timeout.

It retrieves the contents of the URL


Object getContent()
connection.

3.15.1.3 How to get the object of URLConnection Class


The openConnection() method of the URL class returns the object of URLConnection class.
Syntax:
public URLConnection openConnection()throws IOException{}
Example of Java URLConnection Class
import java.io.*;
import java.net.*;
public class URLConnectionExample {
public static void main(String[] args){
try{
URL url=new URL("http://www.javatpoint.com/java-tutorial");
URLConnection urlcon=url.openConnection();
InputStream stream=urlcon.getInputStream();
int i;
while((i=stream.read())!=-1){
System.out.print((char)i);
}
}catch(Exception e){System.out.println(e);}
}
}

Lecture 26
3.16 TCP/IP SERVER SOCKETS

3.16.1 What is a TCP IP socket?

43
TCP/IP creates the socket address as an identifier that is unique throughout all Internet networks. TCP/IP
concatenates the Internet address of the local host interface with the port number to devise the Internet
socket address. With TCP/IP, sockets are not tied to a destination address.

3.16.1.1 What is TCP/IP based server socket in Java?


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.

3.16.1.2 What is socket in Java?


A socket is one end-point of a two-way communication link between two programs running on the network.
Socket classes are used to represent the connection between a client program and a server program.

3.16.1.3 What is a server socket?


Server-Sockets are a type of socket used in network communication for server applications. They are
implemented in Java using the ServerSocket class to handle new client connections efficiently, making it
easy to develop utilities related to network computing and information security.

3.16.2 Why do we need sockets?


Sockets are useful for both stand-alone and network applications. Sockets allow you to exchange information
between processes on the same machine or across a network, distribute work to the most efficient machine,
and they easily allow access to centralized data.

Java has a different socket class that must be used for creating server applications. The ServerSocket 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 constructors for ServerSocket
reflect the port number that you want to accept connections on and, optionally, how long you want the
queue for said port to be. The queue length tells the system how many client connections it can leave
pending before it should simply refuse connections. The default is 50. The constructors might throw an
IOException under adverse conditions. Here are three of its constructors:

44
Figure 3.16 Socket constructor
ServerSocket has a method called accept( ), which is a blocking call that will wait for a client to initiate
communications and then return with a normal Socket that is then used for communication with the
client.
3.17 DATAGRAMS

3.17.1 What is Datagram?


A datagram is an independent, self-contained message sent over the network whose arrival, arrival time,
and content are not guaranteed.
3.17.2 Why is datagram important?
Every datagram carries enough information to let the network forward the packet to its correct
destination; there is no need for any advance setup mechanism to tell the network what to do when the
packet arrives. You just send it, and the network makes its best effort to get it to the desired destination.

3.17.3 What is the use of datagram in Java?


A datagram socket is the sending or receiving point for a packet delivery service. Each packet sent or
received on a datagram socket is individually addressed and routed. Multiple packets sent from one
machine to another may be routed differently, and may arrive in any order.

Java implements datagrams on top of the UDP (User Datagram Protocol) protocol by using two classes:
1. DatagramPacket object is the data container.
2. DatagramSocket is the mechanism used to send or receive the DatagramPackets.

DatagramSocket Class
3.17.4 What is a datagram socket?
A datagram socket provides a symmetric data exchange interface without requiring connection
establishment. Each message carries the destination address. The following figure shows the flow of
communication between server and client. The bind(3SOCKET) step for the server is optional.

3.17.5 What is the difference between socket and datagram in Java?

45
A socket programming construct can use either UDP or TCP transport protocols. Sockets that use UDP
for transport of packets are called “datagram” sockets and sockets that use TCP for transport are called
“stream” sockets.
3.15.6 What are the two types of sockets in java?
There are two different types of sockets present in socket programming, known as server socket and
client socket. The socket present at the client end is called the client socket and on the side of the server
is called the server socket.
DatagramSocket defines four public constructors. They are shown here:
DatagramSocket( ) throws SocketException : It creates a DatagramSocket bound to any unused port
on the local computer.
DatagramSocket(int port) throws SocketException : It creates a DatagramSocket bound to the port
specified by port.
DatagramSocket(int port, InetAddress ipAddress) throws SocketException : It constructs a
DatagramSocket bound to the specified port and InetAddress.
DatagramSocket(SocketAddress address) throws SocketException : It constructs a DatagramSocket
bound to the specified SocketAddress.

Function Usage

If the socket is connected, then the address is returned.


InetAddress getInetAddress( )
Otherwise, null is returned.

int getLocalPort( ) Returns the number of the local port.

Returns the number of the port to which the socket is


int getPort( ) connected. It returns –1 if the socket is not connected
to a port.

Returns true if the socket is bound to an address.


boolean isBound( )
Returns false otherwise.

Returns true if the socket is connected to a server.


boolean isConnected( )
Returns false otherwise.

void setSoTimeout(int millis) Sets the time-out period to the number of milliseconds
throws SocketException passed in millis.

46
3.15.7 DatagramPacket Class
3.15.7.1 What is the use of a datagram packet?
Datagram packets are used to implement a connectionless packet delivery service. Each message is
routed from one machine to another based solely on information contained within that packet. Multiple
packets sent from one machine to another might be routed differently, and might arrive in any order.
3.15.7.2 What is the difference between DatagramSocket and DatagramPacket in Java?
DatagramPacket object is the data container. DatagramSocket is the mechanism used to send or receive
the DatagramPackets.
3.15.7.3 What is the use of DatagramSocket?
The DatagramSocket class supports network communication using a UDP datagram socket. The
DatagramSocket object can be used for client apps that send UDP packets or for server apps that listen
for incoming UDP data. Several steps are needed to send or receive data using a DatagramSocket object.

3.15.7.3 What is the difference between socket and ServerSocket in Java?


A ServerSocket object waits for connections. A Socket object initiates a connection. Socket objects are
used for data transfer.

DatagramPacket defines several constructors. Four are shown here:


DatagramPacket(byte data[ ], int size) : It specifies a buffer that will receive data and the size of a
packet. It is used for receiving data over a DatagramSocket
DatagramPacket(byte data[ ], int offset, int size) : It allows you to specify an offset into the buffer at
which data will be stored.
DatagramPacket(byte data[ ], int size, InetAddress ipAddress, int port) : It specifies a target address
and port, which are used by a DatagramSocket to determine where the data in the packet will be sent.
DatagramPacket(byte data[ ], int offset, int size, InetAddress ipAddress, int port) : It transmits
packets beginning at the specified offset into the data.

Function Usage

Returns the address of the source (for datagrams being


InetAddress getAddress( )
received) or destination (for datagrams being sent).

Returns the byte array of data contained in the datagram.


byte[ ] getData( ) Mostly used to retrieve data from the datagram after it has
been received.

47
Returns the length of the valid data contained in the byte
int getLength( ) array that would be returned from the getData( ) method.
This may not equal the length of the whole byte array.

int getOffset( ) Returns the starting index of the data.

int getPort( ) Returns the port number.

void setAddress(InetAddress Sets the address to which a packet will be sent. The
ipAddress) address is specified by ipAddress.

Sets the data to data, the offset to zero, and the length to
void setData(byte[ ] data)
number of bytes in data

void setData(byte[ ] data, int Sets the data to data, the offset to idx, and the length to
idx, int size) size.

void setLength(int size) Sets the length of the packet to size.

void setPort(int port) Sets the port to port.

Datagrams are bundles of information passed between machines. They are somewhat like a hard throw
from a well-trained but blindfolded catcher to the third baseman. Once the datagram has been released to
its intended target, there is no assurance that it will arrive or even that someone will be there to catch it.
Likewise, when the datagram is received, there is no assurance that it hasn’t been damaged in transit or
that whoever sent it is still there to receive a response.
Java implements datagrams on top of the UDP protocol by using two classes: the DatagramPacket object
is the data container, while the DatagramSocket is the mechanism used to send or receive the
DatagramPackets. Each is examined here.
3.15.8 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

48
The first creates a DatagramSocket bound to any unused port on the local computer. The second creates
a DatagramSocket bound to the port specified by port. The third constructs a DatagramSocket bound to
the specified port and InetAddress. The fourth constructs a DatagramSocket bound to the specified
SocketAddress. SocketAddress is an abstract class that is implemented by the concrete class
InetSocketAddress. InetSocketAddress encapsulates an IP address with a port number. All can throw a
SocketException if an error occurs while creating the socket.
DatagramSocket defines many methods. Two of the most important are send( ) and receive( ), which are
shown here:
void send(DatagramPacket packet) throws IOException
void receive(DatagramPacket packet) throws IOException
The send( ) method sends a packet to the port specified by packet. The receive( ) method waits for a
packet to be received and returns the result.

The following example implements a very simple networked communications client and
server. Messages are typed into the window at the server and written across the network to
the client side, where they are displayed.
// Demonstrate datagrams.
import java.net.*;
class WriteServer {
public static int serverPort = 998;
public static int clientPort = 999;
public static int buffer_size = 1024;
public static DatagramSocket ds;
public static byte buffer[] = new byte[buffer_size];
public static void TheServer() throws Exception {
int pos=0;
while (true) {
int c = System.in.read();
switch (c) {
case -1:
System.out.println("Server Quits.");
ds.close();
49
return;
case '\r':
break;
case '\n':
ds.send(new DatagramPacket(buffer,pos,
InetAddress.getLocalHost(),clientPort));
pos=0;
break;
default:
buffer[pos++] = (byte) c;
}
}
}
public static void TheClient() throws Exception {
while(true) {
DatagramPacket p = new DatagramPacket(buffer, buffer.length);
ds.receive(p);
System.out.println(new String(p.getData(), 0, p.getLength()));
}
}
public static void main(String args[]) throws Exception {
if(args.length == 1) {
ds = new DatagramSocket(serverPort);
TheServer();
} else {
ds = new DatagramSocket(clientPort);
TheClient();
}
}
}
This sample program is restricted by the DatagramSocket constructor to running between
two ports on the local machine. To use the program, run
50
java WriteServer
in one window; this will be the client. Then run
java WriteServer 1
This will be the server. Anything that is typed in the server window will be sent to the client
window after a newline is received.

Questions
1. List 5 features of JavaScript.
2. Explain the difference between client side and server side JavaScript.
3. Write a JavaScript program to find the greatest of three given numbers?
4. What are variables? How to use variables in JavaScript?
5. Explain the difference between String ” …” and null value.
6. Discuss what are functions in JavaScript?
7. Write about data types of variables in JavaScript
8. What are the data types supported by JavaScript?
9. What are the scopes of a variable in JavaScript?
10. In how many ways a JavaScript code can be involved in an HTML file?

11. What is the function of a document.write() method?

12. Explain prompt(), confirm (), alert() functions in JavaScript

13. List some of the advantages and disadvantages of JavaScript.

Programs- Previous Years University Asked Questions(JavaScript)


1. Design a JavaScript program to display the current day and time in the following format. Today is :
Monday. Current time is : 11 AM : 50 : 58
2. Create a program in JavaScript to implement an array of five elements and perform the operations
push, pop, shift, unshift and join on the array.
3. Construct a JavaScript program with three text boxes, two for inputs and one for output, implement
four operations addition, subtraction, multiplication and division on two input numbers on clicking
of buttons ‘add’, ‘subtract’, ‘multiply’ and ‘divide’. Print the result in the output text box.
4. Write a program in JavaScript with two text boxes,one for input and another for output, print first n
terms of Fibonacci series (0, 1, 1, 2, 3, 5, 8, 13, 21, 34…) in output box on clicking of button
‘print’. Input n is given in input box

51
5. Create a JavaScript program to make an arithmetic calculator.
6. Design an educational website having four pages. First page should be a homepage having
information of the college, Images and Links for the other pages like contacts, Courses (Give the
list of different courses) and registration form (name, father name, email id and phone number).
Apply validation on all the fields (name, father name, email id and phone number).
7. Design a HTML form with name, address, pincode and password. Outline a JavaScript code that
can validate on following constraints: a. No fields must be left blank b. Pincode must be numeric
and contain 6 digits c. Password field (i) At least contains 1 Capital letter. (ii) Minimum length 8
characters
8. Design a HTML form with name, address, pincode and password. Outline a JavaScript code that
can validate on following constraints: a. No fields must be left blank b. Pincode must be numeric
and contain 6 digits c. Password field (i) At least contains 1 Capital letter. (ii) Minimum length 8
characters
9. Outline a JS function that takes 4 variables, a, b, c, d, and prints true in an alert box if input a >
input b and input c > input d. Else, print false in an alert box.

52

You might also like