Unit-3 Javascript
Unit-3 Javascript
Lecture 19:
3.1 JAVASCRIPT: INTRODUCTION
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
<head>
3
<title>
Basic Example to Describe JavaScript
</title>
</head>
<body>
</html>
Output: The output will display on the console.
Welcome to JavaScript
3.2 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.
When we want to write some string on web page then we use document.
Example-
4
<!DOCTYPE html>
<html>
<head>
<title>Hello, World!</title>
</head>
<body>
<script type="text/javascript">
document.write("hello everyone");
</script>
</body>
</html>
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());
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.
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.
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:
7
Null represents null i.e. no value at all
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
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
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
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
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.
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.
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>";
}
13
Inside the function, the arguments (the parameters) behave as local variables.
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;
}
function myFunction() {
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
}
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:
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";
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
20
It is used to fetch the part of the given string on the
substr()
basis of the specified starting position and length.
It trims the white space from the left and right side of
trim()
the string.
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.
<script>
document.write(10<20);//true
document.write(10<5);//false
</script>
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.
A synchronous request blocks the client until operation completes i.e. browser is unresponsive. In such
case, javascript engine of the browser is blocked.
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.
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.
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
IP Address
Method Description
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:
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.
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
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
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);}
}
}
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 boolean equals(Object obj) it compares the URL with the given object.
40
public Object getContent() it returns the content of the URL.
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
Constructor Description
Method Description
42
int getConnectionTimeout() It returns setting for connect timeout.
Lecture 26
3.16 TCP/IP SERVER SOCKETS
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.
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
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.
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
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.
Function Usage
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.
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.
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?
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