Back to Study material
WT

Unit 3

Scripting

 


 

JavaScript is a dynamic programming language for computers. It is a lightweight component of web pages whose implementations allow client-side scripts to communicate with users and create dynamic pages. It's an object-oriented programming language that can be interpreted.

 

JavaScript is a lightweight, cross-platform object-based scripting language.

JavaScript is a translated language, not a compiled language. The JavaScript Translator (which is built into the browser) is in charge of translating JavaScript code for web browsers.

 

JavaScript (js) is a lightweight object-oriented programming language that is used to script webpages by a number of websites. When applied to an HTML document, it is an interpreted, full-featured programming language that enables dynamic interactivity on websites.

 

It was first released in 1995 to enable users to add programs to webpages in the Netscape Navigator browser. Since then, all other graphical web browsers have followed it. Users can use JavaScript to create modern web applications that communicate directly without having to reload the page every time. Js is used on a typical website to include various ways of interactivity and simplicity.

 

Documents

The Document interface represents any web page loaded in the browser and acts as a portal to the web page's content, which is represented by the DOM tree. The DOM tree contains a variety of elements, including and. It gives the document global features, such as how to get the page's URL and add new elements to the document.

 

The Paper interface defines the properties and methods that are common to all types of documents. A wider API is accessible depending on the document type (e.g., HTML, XML, SVG, etc.): The HTMLDocument interface is also implemented by HTML documents served with the "text/html" content form, while the XMLDocument interface is implemented by XML and SVG documents.

 

Forms

JavaScript is capable of validating HTML forms.

 

This function alerts a message and returns false if a form field (fname) is empty, preventing the form from being submitted:

 

Example:

function validateForm () {

  var x = document.forms["myForm”] ["fname"].value;

  if (x == "") {

 alert ("Name must be filled out");

    return false;

  }

}

 

Statements

These programming instructions are known as statements in a programming language.

A list of programming statements makes up a JavaScript program.

 

Values, Operators, Expressions, Keywords, and Comments make up JavaScript statements.

 

Example:

var a, b, c; // Statement 1

x = 8;         // Statement 2

y = 4;         // Statement 3

z = x + y;   // Statement 4

 

Functions

A JavaScript function is a piece of code that performs a specific task.

 

When "something" calls a JavaScript method, it is executed (calls it).

 

The function keyword is used to describe a JavaScript function, which is then followed by a name and parentheses ().

 

Letters, numbers, underscores, and dollar signs can all be used in function names (same rules as variables).

 

Parameter names separated by commas can be used in the parentheses: (parameter1, parameter2, ...)

 

The function's code to be executed is enclosed in curly brackets: {}

function name (parameter1, parameter2, parameter3) {

  // code to be executed

}

 

Objects

A javaScript object is a state and behavior-based entity (properties and method). For example, a car, a pen, a bicycle, a chair, a bottle, a keyboard, and a monitor.

 

JavaScript is an object-oriented programming language. In JavaScript, everything is an entity.

 

JavaScript is a template-based language, not a class-based language. To get the object, we don't need to build a class. However, we guide the creation of things.

 

Creating objects

Objects can be made in three different ways.

 

  • By object literal
  • The following is the syntax for constructing an object with an object literal:

    object= {property1:value1, property 2: value2....propertyN:valueN}

     

    2.     By creating instance of Object directly (using new keyword)

    The syntax for explicitly constructing an object is as follows:

    var objectname=new Object ();

     

    3.     By using an object constructor (using new keyword)

    You must construct a function with arguments in this case. This keyword can be used to assign each argument value to the current object.

    The current object is referred to by this keyword.

    Key takeaway:

  • JavaScript is a dynamic programming language for computers.
  • JavaScript is a lightweight, cross-platform object-based scripting language.
  • It was first released in 1995 to enable users to add programs to webpages in the Netscape Navigator browser.
  • A JavaScript function is a piece of code that performs a specific task.
  • A javaScript object is a state and behavior-based entity.
  •  

     


    The acronym Ajax stands for Asynchronous JavaScript and XML. It's used to connect with the server without having to refresh the tab, resulting in a better user experience and efficiency.

     

    It's a set of technologies that work together, such as JavaScript, DOM, XML, HTML/XHTML, CSS, and XMLHttpRequest.

     

    You can use AJAX to send and receive data asynchronously without having to reload the tab. As a result, it is fast.

     

    You may use AJAX to send only the most relevant information to the server, rather than the whole page. As a result, only the most important data from the client is sent to the server. It improves the interactivity and speed of your application.

     

    Yahoo, Facebook, Twitter, Google Maps, and YouTube are only a few examples of web applications that use ajax technology.

     

    AJAX is a web-based application that employs a mixture of:

            XMLHttpRequest object (to exchange data asynchronously with a server)

            JavaScript/DOM (to display/interact with the information)

            CSS (to style the data)

            XML (often used as the format for transferring data)

     

    Fig 1: working of AJAX

    Key takeaway:

  • The acronym Ajax stands for Asynchronous JavaScript and XML.
  • You can use AJAX to send and receive data asynchronously without having to reload the tab. As a result, it is fast.
  •  

     


    An IP stands for internet protocol. An IP address is assigned to each device connected to a network. Each device uses an IP address for communication. It also behaves as an identifier as this address is used to identify the device on a network. It defines the technical format of the packets. Mainly, both the networks, i.e., IP and TCP, are combined together, so together, they are referred to as TCP/IP. It creates a virtual connection between the source and the destination.

    We can also define an IP address as a numeric address assigned to each device on a network. An IP address is assigned to each device so that the device on a network can be identified uniquely. To facilitate the routing of packets, TCP/IP protocol uses a 32-bit logical address known as IPv4(Internet Protocol version 4).

     

    Function:

    The internet protocol's main purpose is to provide hosts with addresses, encapsulate data into packet structures, and route data from source to destination through one or more IP networks. The internet protocol provides two main items in order to achieve these functionalities, which are mentioned below.

          Format of IP packet

          IP Addressing system

    IP packet

    Until an IP packet is sent over the network, it contains two main components: a header and a payload.

    Fig 2: IP packet

     

    An IP header provides a lot of details about the IP packet, such as:

          The source IP address is that of the person who is sending the data.

          IP address of the destination: The destination is a host that collects data from the sender.

          Header length

          Packet length

          TTL (Time to Live) of a packet is the amount of hops that must occur before the packet is discarded.

          The internet protocol's transport protocol, which can be TCP or UDP, is known as the transport protocol.

    The IP header contains a total of 14 fields, one of which is optional.

     

    The data to be transported is known as the payload.

    Key takeaway:

  • The internet protocol's main purpose is to provide hosts with addresses, encapsulate data into packet structures, and route data from source to destination through one or more IP networks.
  • An IP address is assigned to each device connected to a network. Each device uses an IP address for communication.
  •  

     


    Both the numerical IP address and the domain name for that address are encapsulated in the InetAddress class. This class is interacted with by using an IP host's name, which is more convenient and understandable than its IP address. The number is hidden within the InetAddress class. Both IPv4 and IPv6 addresses are supported by InetAddress.

     

    The java.net framework. The IP address is encapsulated in Java's InetAddress class. Most other networking classes, such as Socket, ServerSocket, URL, DatagramSocket, DatagramPacket, and others, use it.

     

    public final class InetAddress extends Object implements Serializable

     

    This class has two fields that represent an Internet address: hostName (a String) and address (an int). The name of the host is included in hostName.

     

    Creating New InetAddress Objects

    The InetAddress class does not have any public constructors. InetAddress, on the other hand, has three static methods that, given a little detail, return appropriately initialized InetAddress items. They are as follows:

     

    public static InetAddress InetAddress.getByName(String hostName)

     throws UnknownHostException

    public static InetAddress [] InetAddress.getAllByName(String hostName)

     throws UnknownHostException

    public static InetAddress InetAddress.getLocalHost()

     throws UnknownHostException

     

    To fill out the information in the InetAddress object, all three of these may link to the local DNS server.

     

    Method

    Description

    public static InetAddress getByName (String host) throws UnknownHostException

    It returns an instance of InetAddress with the IP and name of the LocalHost.

    public static InetAddress getLocalHost () throws UnknownHostException

    It returns an InetAddress instance with the local host name and address.

    public String getHostName ()

    It returns the IP addresses hostname.

    public String getHostAddress ()

    The IP address is returned as a string.

     

    Key takeaway:

  • Both the numerical IP address and the domain name for that address are encapsulated in the InetAddress class.
  • The InetAddress class does not have any public constructors.
  •  

     


    There are no visible constructors in the InetAddress class. You must use one of the available factory methods to build an InetAddress object. Static methods in a class that return an instance of that class are known as factory methods. When having specific method names makes the results much simpler, this is achieved instead of overloading a constructor with different parameter lists. Here are three widely used InetAddress factory methods:

     

    The InetAddress object that represents the local host is returned by the getLocalHost () process. For a host name passed to it, the getByName () method returns an InetAddress.

     

    On the Internet, it's popular to see a single name representing several machines. This is one way to have a degree of scaling in the world of web servers. The factory method getAllByName( ) returns an array of InetAddresses that represents all of the addresses that a given name resolves to. If it can't resolve the name to at least one address, it'll throw an UnknownHostException.

     

    The factory method getByAddress( ), which takes an IP address and returns an InetAddress object, is also included in InetAddress. You can use either an IPv4 or IPv6 address.

     

    The addresses and names of the local computer, as well as two Internet web pages.

     

    // 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]);

    }

    }

     

    This program's performance can be shown below. (Of course, the results you see can vary slightly.)

     

    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

     

    Key takeaway:

  • There are no visible constructors in the InetAddress class.
  • You must use one of the available factory methods to build an InetAddress object.
  • The factory method getByAddress( ), which takes an IP address and returns an InetAddress object, is also included in InetAddress.
  •  

     


    There are some other methods in the InetAddress class that can be used on the objects returned by the methods. Here are a few of the most common methods:

     

    boolean equals (Object other): Returns true if this object has the same Internet address as other.

     

    byte [ ] getAddress( ) : Returns a byte array that represents the object’s IP address in network byte order.

     

    String getHostAddress( ) : Returns a string that represents the host address associated with the InetAddress object.

     

    String getHostName( ) : Returns a string that represents the host name associated with the InetAddress object.

     

    boolean isMulticastAddress( ) : Returns true if this address is a multicast address. Otherwise, it returns false.

     

    String toString( ) : Returns a string that lists the host name and the IP address for convenience.

    Fig 3: methods

    A sequence of hierarchically cached servers is used to look up Internet addresses. That means your local computer can automatically recognize a specific name-to-IP-address mapping, such as for itself and nearby servers. It can ask a local DNS server for IP address information for other names. If that server doesn't have a specific address, it may request one from a remote location. This procedure can be followed all the way to the root server.

     

    Key takeaway:

  • There are some other methods in the InetAddress class that can be used on the objects returned by the methods.
  • A sequence of hierarchically cached servers is used to look up Internet addresses.
  •  

     


    A TCP/IP client socket connects two computers on a network in a secure, bi-directional, stream-based link. An instance of the Socket class is used to implement the client socket. Its aim is to establish a connection to the server and initiate protocol exchanges.

     

    TCP/IP sockets are used to create stable, bidirectional, permanent, point-to-point, stream-based connections between Internet hosts. A socket connects Java's I/O device to other programs running on the local computer or on some other machine connected to the Internet.

     

    In Java, there are two types of TCP sockets. The first is for servers, and the second is for clients. The ServerSocket class is intended to function as a "listener," meaning it will wait for clients to communicate before proceeding. As a result, ServerSocket is only for servers. Clients use the Socket class. Its purpose is to establish connections to server sockets and initiate protocol exchanges.

     

    Methods to Create TCP Client Sockets

    These methods can be used to build a Socket class object:

     

          By using the following hostname and port number:

     

    Socket (String hostname1, int port1)

    Where hostname1 is a string style variable referring to the destination address, and port1 is the destination address's port number. In the event of an error, this method will throw the UnknownHostException or IOException exceptions.

     

          By using the following syntax to define an InetAddress object and a port number:

     

    Socket (InetAddress ipaddr1, int port1)

    Where ipaddr1 is an item of the InetAddress class, and port1 is the destination's port number. In the event of an error, this method will throw the IOException exception.

     

    Method of the Socket Class

     

    InetAddress getInetAddress() -- Returns the InetAddress that is associated with the socket object.

     

    int getPort() -- Returns the port number on which the socket is connected

     

    int getLocalPort() -- Returns the local port number on which the socket is created

     

    InputStream getInputStream() -- Returns the InputStream associated with the calling object.

     

    OutputStream getOutputStream() -- Returns the OutputStream associated with the calling object.

     

    void close () -- Closes the InputStream () and OutputStream () of the socket.

     

    Example: Client Side Code

    import java.net.*;

    import java.io.*;

    class clientsock

    {

     public static void main (String args []) throws IOException

     {

      System.out.println("sending request to server....");

      Socket client=new Socket ("127.0.0.1",1235);

      System.out.println("successfully connected");

      BufferedReader br1=new BufferedReader (new InputStreamReader (System.in));

      PrintStream ps=new PrintStream(client.getOutputStream());

      BufferedReader br=new BufferedReader (new InputStreamReader(client.getInputStream()));

      while(true)

      {

       System.out.println("input the data u want to send to echo server: ");

       String s=br1.readLine();

       ps.println(s);

       if(s.equals("exit"))

       {

        System.exit(1);

       } 

       String st=br.readLine();

       System.out.println("data returned by the server:   ");

       System.out.println(st);

      }

     }

    }

     

    Key takeaway:

  • A TCP/IP client socket connects two computers on a network in a secure, bi-directional, stream-based link.
  • An instance of the Socket class is used to implement the client socket.
  •  Its aim is to establish a connection to the server and initiate protocol exchanges.
  •  

     


    The Uniform Resource Locator (URL) is a format for specifying addresses on the World Wide Web. A URL is the most basic network identifier for any resource on the internet (e.g., hypertext pages, images, and sound files).

     

    The URL is a relatively comprehensible format for identifying or addressing information on the Internet. URLs are everywhere; they're used by every browser to find information on the Internet. The URL class in Java's network class library provides an easy, succinct API for accessing information over the Internet via URLs.

     

    An URL is represented by the Java URL class. Uniform Resource Locator is an acronym for Uniform Resource Locator. It directs you to a World Wide Web resource.

     

    Constructor of java URL Class

    URL (string spec)

    From the String representation, creates an instance of a URL.

     

    URL (String protocol, String host, int port, String file)

    From the specified protocol, host, port number, and file, creates an instance of a URL.

     

    URL (String protocol, String host, int port, String file, URLStreamHandler handler)

    Creates a URL from the protocol, host, port number, file, and handler arguments.

     

    URL (String protocol, String host, String file)

    From the specified protocol name, host name, and file name, creates an instance of a URL.

     

    URL (URL context, String spec)

    By parsing the given spec within a given context, this method creates an instance of a URL.

     

    URL (URL context, String spec, URLStreamHandler handler)

    By parsing the given spec with the specified handler within a given context, this method creates an instance of a URL.

     

    URL Connection

    A communication link between the URL and the application is represented by the Java URLConnection class. This class can be used to read and write data to the URL-referenced resource defined.

     

    An active link to a resource defined by a URL is represented by the abstract class URLConnection. The URLConnection class serves two distinct but complementary purposes. For starters, it gives you more control over how you communicate with a server than the URL class does. You may inspect the MIME headers sent by an HTTP server and react appropriately using a URLConnection.

     

    The MIME header fields used in the client request may be modified. A URLConnection can be used to import binary files. Finally, a URLConnection allows you to use POST and PUT to send data back to a web server, as well as other HTTP request methods.

     

    Second, like the URLStreamHandler class, the URLConnection class is part of Java's protocol handler mechanism. Protocol handlers have a basic concept: they distinguish the details of processing a protocol from the details of processing specific data types, providing user interfaces, and other tasks that a monolithic web browser performs. Java.net is the foundation.

     

    The URLConnection class is abstract; you must create a subclass to enforce a particular protocol. These subclasses may be loaded at runtime by your own applications or the HotJava browser; in the future, Java applications will be able to download protocol handlers as required over the Internet, allowing them to be automatically extensible.

     

    How to get the object of URLConnection class

    The URL class's openConnection () method returns a URLConnection item. The syntax is as follows:

    public URLConnection openConnection () throws IOException {}

     

    Displaying source code of a webpage by URLConnecton class

    Using the getInputStream () method of the URLConnection class, we may show all of the data from a webpage. The getInputStream () method returns all of the data in the stream that can be read and displayed for the given URL.

     

    Example:

    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);} 

    } 

    } 

     

    Key takeaway:

  • The Uniform Resource Locator (URL) is a format for specifying addresses on the World Wide Web.
  • A URL is the most basic network identifier for any resource on the internet.
  • A communication link between the URL and the application is represented by the Java URLConnection class.
  • This class can be used to read and write data to the URL-referenced resource defined.
  •  

     


    For server applications, Java has a separate socket class that must be used. The ServerSocket class is used to build servers that listen on published ports for connections from local or remote client programs. Server Sockets are not the same as regular Sockets.

     

    When you build a ServerSocket, it will inform the device that it is interested in receiving client connections. Server Socket’s constructors represent the port number on which you want to accept connections and, optionally, the length of the queue for that port.

     

    The queue length informs the machine how many pending client connections it will keep before simply rejecting them. The default is 50. Under certain circumstances, the constructors can throw an IOException.

     

    Three of its constructors are as follows:

    Fig 4:  constructor

    Accept () is a blocking method on ServerSocket that waits for a client to initiate communication before returning with a regular Socket that can be used to communicate with the client.

     

    Key takeaway:

  • For server applications, Java has a separate socket class that must be used.
  • Server Sockets are not the same as regular Sockets.
  •  

     


    TCP/IP networking is suitable for the majority of networking requirements. It generates a stream of packet data that is serialized, predictable, and dependable. However, there is a price to pay for this. TCP requires a number of complex algorithms for congestion management on congested networks, as well as negative packet loss predictions. As a result, data is transported in an inefficient manner. Datagrams are a different choice.

     

    Datagrams are information packets that are sent between computers. They resemble a hard throw to the third baseman from a well-trained yet blindfolded catcher.

    There is no guarantee that the datagram will arrive at its intended destination or that anyone will be there to catch it after it has been posted. Similarly, there is no guarantee that the datagram was not destroyed in transit or that the person who sent it is still alive to receive an answer when it is received.

     

    Java uses two groups to implement datagrams on top of the UDP protocol: the DatagramPacket object is the data container, and the DatagramSocket is the mechanism for sending and receiving Datagram Packets.

     

    DatagramSocket

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

     

    DatagramSocket (int port) throws SocketException

    DatagramSocket (int port, InetAddress ipAddress) throws SocketException DatagramSocket (SocketAddress address) throws SocketException

    The first creates a DatagramSocket on the local machine that is connected to any unused port. The second generates a DatagramSocket with port as its destination. The third creates a DatagramSocket with the required InetAddress and port. The fourth creates a

     

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

     

    Many methods are described by DatagramSocket. Send () and receive (), two of the most common, are seen here:

     

    void send (DatagramPacket packet) throws IOException void receive (DatagramPacket packet) throws IOException

     

    Fig 5: other method of datagram socket

    Key takeaway:

  • Datagrams are information packets that are sent between computers.
  • They resemble a hard throw to the third baseman from a well-trained yet blindfolded catcher.
  • Data is transported in an inefficient manner. Datagrams are a different choice.
  •  

    Reference:

  • Burdman, Jessica, “Collaborative Web Development” Addison Wesley
  • Xavier, C, “Web Technology and Design”, New Age International
  • Ivan Bayross,” HTML, DHTML, Java Script, Perl & CGI”, BPB Publication
  • Bhave, “Programming with Java”, Pearson Education
  • Herbert Schieldt, “The Complete Reference: Java”, McGraw Hill.

  • Index
    Notes
    Highlighted
    Underlined
    :
    Browse by Topics
    :
    Notes
    Highlighted
    Underlined