You are on page 1of 124

NETWORK PROGRAMMING

LABORATARY MANUAL

Amal P.M Nithish Divakar Rakesh K.R Vishnu M Santosh

Departement Of Computer Science And Engineering


Government Engineering College, Idukki

Preface
The book named Network Programming Laboratory Manual is designed in connection with the network programming lab in the Seventh Semester Computer Science and Engineering. Attempts have been made to present network concepts, Berkeley sockets, network programming in java, Java Database Connectivity(JDBC), Remote method invocation(RMI), Extensile Markup language(XML), Java Server pages(JSP) etc. In addition, examples in areas of Connection oriented communication, connection less communication, JDBC, Remote Method Invocation, XML and Java Server Pages have been worked out in this record. The major features of the record are 1. Simple presentation 2. Coverage of network related packages in java. 3. Explanations of networking concepts, JDBC, RMI, XML, JSP etc. 4. Illustrative examples The record is organized as three parts In Part I, the essential concepts related to Computer network, protocols and network models are explained. Part II contains the topics of network programming in java, JDBC, RMI, XML, JSP etc. Part III layout illustrative examples of the technologies in Part II. Part IV list all reference materials which have been used to develop this record

Disclaimer
This work has been prepared with no intention of producing a prot. On the course of producing this material, we have referred many websites as well as several text books each of them have been acknowledged in last part of this book. The materials in this book is correct to our knowledge. However we assume no responsibility if the material proved to be faulty or incorrect. The reader is advised to check other valid sources before assuming the correctness of materials provided here with.

Acknowledgement
This work is the output of the sincere eorts we have made for one semester. We express the Almighty for the blessings incurred on us for the preparation of this work. The book is fully developed in the Laboratories of Govt. Engineering College, Idukki. We express our sincere gratitude to the faculty and other sta of Govt. engineering College, Idukki for their help and coordination. We also express our sincere thanks to all including our parents and friends who have helped us directly or indirectly in the preparation of this manual.
A Finally we also thank Donal E Knuth and Leslie Lamport for creating TEX and L TEX as without these softwares, our work would have never seen completion.

Amal P M Nithish Divakar Rakesh K R Vishnu M Santosh


Students of Computer Science and Engineering 2009-2013 batch Govt. Engineering College, Idukki

Contents
Basic Concepts of Networking
1 Basic Concepts of Networking 1.1 Addressing . . . . . . . . . . 1.2 Protocols . . . . . . . . . . . 1.3 Network Models . . . . . . . 2 Networking Hardwares 2.1 Gateway . . . . . . . 2.2 Router . . . . . . . . 2.3 Bridge . . . . . . . . 2.4 Switch . . . . . . . . 2.5 Hubs . . . . . . . . . 2.6 Repeaters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

9
11 11 11 13 15 15 15 16 16 16 17

Networking Technologies
3 Berkeley Socket . . . . . . . . . . . 3.1 Berkeley Socket API . . . . . . . 3.2 Header Files . . . . . . . . . . . . 3.3 Methods of Berkeley Socket API 3.4 Modes of Berkeley Sockets . . . . 4 Networking in java . . . 4.1 Network Programming 4.2 Java.net Package . . . 4.3 Java.rmi Package . . . 4.4 Java.sql Package . . . . . . . . . and Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

19
21 21 21 21 23 25 25 25 28 29 31 31 31 32 33 35

5 Java Server Pages . . . . . . . 5.1 Introduction to JSP . . . . 5.2 Advantages of JSP . . . . . 5.3 How JSP Works . . . . . . 5.4 Components of a JSP page

6 Extended Markup Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

CONTENTS 6.1 6.2 6.3 6.4 6.5 What is XML . . . . . . . . . . . . Structure of XML Document. . . . Components of an XML Document Syntax rules of XML . . . . . . . . Advantages of using XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 35 35 37 38 39 39 39 40 40 41

7 Applets . . . . . . . . . . . . . 7.1 Java Applet . . . . . . . . 7.2 Capabilities of an Applet 7.3 Advantages . . . . . . . . 7.4 Applet Architecture . . . 7.5 The HTML APPLET Tag

Experiments
8 Connecting Two Computers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 Berkeley Socket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10 Echo Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Chatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12 File Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 UDP Messaging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 Broadcasting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 Remote Method Invocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 Java Database Connectivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 Extended Markup Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18 Java Server Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 Java Applet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

43
45 49 55 61 67 73 77 81 85 89 93 99

20 HTTP Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103 21 HTTP Client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 22 Implementation of Ping Command . . . . . . . . . . . . . . . . . . . . . . . . . . 115

References

119

23 Book References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 24 Web References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 8

Created by

Amal, Nithish, Rakesh & Vishnu

Part I

Basic Concepts of Networking

Basic Concepts of Networking


A computer network, or simply a network, is a collection of computers interconnected by communication channels that allow sharing of resources and information. Hence a network is a framework in which the connected machines can exchange information. This requirement raises issues like how each machine is individually identied, how the data is exchanged between machine, how the communication is actually conducted etc. Addressing these issues, several networking standards related to addressing schemes, communication protocols, connection paradigms etc. have been developed. Also, based on how a machine acts during its communication gave rise to development of two distinct network models; client server model and peer to peer model.

1.1

Addressing

Every machine connected to the network is uniquely identied by a 4-byte address called Internet Protocol address . This is typically written in dotted quad format like 128.250.25.158 where each byte is an unsigned value between 0 and 255. But a machine in network may be required to provide many services at same time. To distinguish these services, a concept of ports, a logical access point, represented by a 16-bit integer number is used. That means, each service oered by a machine is uniquely identied by a port number.

1.2

Protocols

Communications protocols denes the syntax, semantics for exchanging information in a computer network. Communication Protocols addresses many issues like Data formats and Address Formats for Data exchange, Address mapping and Detection of transmission errors. Protocols may include signaling, authentication and error detection and correction capabilities. As far as networking is concerned, all communication protocol can be broadly classied into connectionoriented and connectionless protocol

Connection-oriented Protocols
A connection-oriented protocol is a protocol which established a connection to the receiver and then only send the required data. The connection path maybe a circuit switched connection, 11

CHAPTER 1. BASIC CONCEPTS OF NETWORKING or a virtual circuit connection in a packet switched network. Connection oriented protocol can be made to deliver data in same order as they were sent and they can also guarantee error free transmission by implementing error detection and correction schemes. Because they rst setup a connection to the host initially, they are substantially slower than there connectionless counter parts. But they are useful in uninterrupted and secure transmissions. Some of connectionoriented protocols are: Transmission Control Protocol(TCP) TCP provides reliable, ordered delivery of a stream of octets from a program on one computer to another program on another computer. TCP is the protocol used by major Internet applications such as the World Wide Web, email, remote administration and le transfer. Simple Mail Transfer Protocol (SMTP) SMTP is an Internet standard for electronic mail (e-mail) transmission across Internet Protocol (IP) networks. Asynchronous Transfer Mode (ATM) ATM uses asynchronous time-division multiplexing, and it encodes data into small, xedsized cells. ATM uses a connection-oriented model in which a virtual circuit must be established between two endpoints before the actual data exchange begins. ATM is a core protocol used over the SONET/SDH backbone of the public switched telephone network (PSTN) and Integrated Services Digital Network (ISDN).

Connectionless Protocols
Connectionless protocols allow communication between two network end points in which a message can be sent from one end point to another without prior arrangement. The device at one end of the communication transmits data addressed to the other, without rst ensuring that the recipient is available and ready to receive the data. Some protocols allow for error correction by requested retransmission. Some connectionless protocols are: Hypertext Transfer Protocol (HTTP) HTTP is an application protocol for distributed, collaborative, hypermedia information systems. HTTP is the foundation of data communication for the World Wide Web. HTTP is the protocol to exchange or transfer hypertext. HTTP functions as a request-response protocol in the client-server computing model. A web browser, for example, may be the client and an application running on a computer hosting a web site may be the server. The client submits an HTTP request message to the server. The server, which provides resources such as HTML les and other content, or performs other functions on behalf of the client, returns a response message to the client. The response contains completion status information about the request and may also contain requested content in its message body. User Datagram Protocol (UDP) UDDP is one of the core members of the Internet protocol suite, the set of network protocols used for the Internet. With UDP, computer applications can send messages, in this case referred to as datagrams, to other hosts on an Internet Protocol (IP) network without prior communications to set up special transmission channels or data paths. Internet Protocol (IP) Internet Protocol is the principal communications protocol used for relaying datagrams 12
Created by

Amal, Nithish, Rakesh & Vishnu

CHAPTER 1. BASIC CONCEPTS OF NETWORKING (also known as network packets) across an internetwork using the Internet Protocol Suite responsible for routing packets across network boundaries. It is the primary protocol that establishes the Internet.

1.3

Network Models

Based on how communication between two machines in a network is achieved, the mode of communication can be classied as connection oriented and connection-less. In connection oriented mode, two machines must establish an implicit connection between them to communicate where as in connection-less mode, communication progresses without establishing implicit connections.

Client-Server Model
The client/server model is a computing model in which clients request services provided by server. A client does not share any of its resources, but requests a servers content or service function. Clients therefore initiate communication sessions with servers which await incoming requests.

Figure 1.1: Client-Server Model

Peer-To-Peer Model
A peer-to-peer (abbreviated to P2P) computer network is one in which each computer in the network can act as a client or server for the other computers in the network, allowing shared access to various resources such as les, peripherals, and sensors without the need for a central server. P2P is a distributed application architecture that partitions tasks or workloads among peers. Peers are equally privileged participants in the application. Each computer in the network is referred to as a node. The owner of each computer on a P2P network would set aside a portion of its resources - such as processing power, disk storage, or network bandwidth - to be made directly available to other network participant, without the need for central coordination by servers or stable hosts.

Created by

13

Amal, Nithish, Rakesh & Vishnu

Networking Hardwares
Networking hardware or networking equipment typically refers to devices facilitating the use of a computer network. Typically, this includes gateways, routers, network bridges, switches, hubs, and repeaters. Computer networking devices are also called network equipment, Intermediate Systems (IS) or InterWorking Unit (IWU). Units which are the last receiver or generate data are called hosts or data terminal equipment. The most common kind of networking hardware today is copper-based Ethernet adapters, helped largely by its standard inclusion on most modern computer systems.

2.1

Gateway

A gateway is a network point that acts as an entrance to another network. A gateway may contain devices such as protocol translators, impedance matching devices, rate converters, fault isolators, or signal translators as necessary to provide system interoperability. It also requires the establishment of mutually acceptable administrative procedures between both networks. A protocol translation/mapping gateway interconnects networks with dierent network protocol technologies by performing the required protocol conversions. While forwarding an IP packet to another network, the gateway might or might not perform Network Address Translation.

2.2

Router

A router is a device that forwards data packets between computer networks, creating an overlay internetwork. A router is connected to two or more data lines from dierent networks. When a data packet comes in one of the lines, the router reads the address information in the packet to determine its ultimate destination. Then, using information in its routing table or routing policy, it directs the packet to the next network on its journey. Routers perform the trac directing functions on the Internet. When multiple routers are used in interconnected networks, the routers exchange information about destination addresses, using a dynamic routing protocol. Each router builds up a table listing the preferred routes between any two systems on the interconnected networks. A router has interfaces for dierent physical types of network connections, (such as copper cables, ber optic, or wireless transmission). 15

CHAPTER 2. NETWORKING HARDWARES

2.3

Bridge

A network bridge is a network device that connects more than one network segment. In the OSI model bridging acts in the rst two layers. There are four types of network-bridging technologies: simple bridging; multiport bridging; learning, or transparent bridging; and source route bridging. Network bridges work similarly to network switches, but the trac is managed dierently. A bridge will only send trac from one side to the other if it is going to a destination on the other side. This is dierent to a layer 1 switch which sends all trac from either side. Sometimes network bridges are called layer 2 switches. Since they need to look at the contents of the trac going into them, they are much more complicated than a hub or repeater

2.4

Switch

A network switch is a computer networking device that links network segments or network devices. The term commonly refers to a multi-port network bridge that processes and routes data at the data link layer (layer 2) of the OSI model. Switches receives a message from any device connected to it and then transmits the message only to the device for which the message was meant. This makes the switch a more intelligent device than a hub (which receives a message and then transmits it to all the other devices on its network). Switches may operate at one or more layers of the OSI model, including data link and network. A device that operates simultaneously at more than one of these layers is known as a multilayer switch.

Figure 2.1: Switch

2.5

Hubs

An Ethernet hub or hub is a device for connecting multiple Ethernet devices together and making them act as a single network segment. It has multiple input/output (I/O) ports, in which a signal introduced at the input of any port appears at the output of every port except the original incoming. A hub works at the physical layer (layer 1) of the OSI model. A hub does not examine or manage any of the trac that comes through it: any packet entering any port is rebroadcast on all other ports. It is barely aware of frames or packets and mostly operates on raw bits or symbols. Consequently, due to the larger collision domains, packet collisions are more frequent in networks connected using hubs than in networks connected using more sophisticated devices. 16
Created by

Amal, Nithish, Rakesh & Vishnu

CHAPTER 2. NETWORKING HARDWARES Hubs are classied as physical layer devices in the OSI model. At the physical layer, hubs support little in the way of sophisticated networking. Hubs do not read any of the data passing through them and are not aware of their source or destination addressing. A hub simply receives incoming Ethernet frames, regenerates the electrical signal on the bit (more precisely the symbol) level, and broadcasts these symbols out to all other devices on the network.

Figure 2.2: Network Hub

2.6

Repeaters

A repeater is an electronic device that receives a signal and retransmits it at a higher level or higher power, or onto the other side of an obstruction, so that the signal can cover longer distances. In telecommunication,repeater can be ann analog device that amplies an input signal regardless of its nature (analog or digital) or a digital device that amplies, reshapes, retimes, or performs a combination of any of these functions on a digital input signal for retransmission. In computer networking, because repeaters work with the actual physical signal, and do not attempt to interpret the data being transmitted, they operate on the physical layer, the rst layer of the OSI model. Repeaters are used to boost signals in coaxial and twisted pair cable and in optical ber lines. An electrical signal in a cable gets weaker the further it travels, due to energy dissipated in conductor resistance and dielectric losses. Similarly a light signal traveling through an optical ber suers attenuation due to scattering and absorption. In long cable runs, repeaters are used to periodically regenerate and strengthen the signal.

Created by

17

Amal, Nithish, Rakesh & Vishnu

Part II

Networking Technologies

19

Berkeley Socket
3.1 Berkeley Socket API

A socket API is an application programming interface (API), usually provided by the operating system, that allows application programs to control and use network sockets. Berkeley sockets (or BSD sockets) is a computing library with an application programming interface (API) for internet sockets and Unix domain sockets, used for inter-process communication (IPC). Berkeley Socket API is a networking API in C. It allows creation of sockets which acts as a standard interface between network and application.

3.2

Header Files

The services of Berkeley Socket API is provided to application programmers through 5 header ies. They are 1. < sys/socket.h > Core BSD socket functions and data structures. 2. < netinet/in.h > AF INET and AF INET6 address families and their corresponding protocol families PF INET and PF INET6. Widely used on the Internet, these include IP addresses and TCP and UDP port numbers. 3. < sys/un.h > PF UNIX/PF LOCAL address family. Used for local communication between programs running on the same computer. Not used on networks. 4. < arpa/inet.h > Functions for manipulating numeric IP addresses. 5. < netdb.h > Functions for translating protocol names and host names into numeric addresses. Searches local data as well as DNS.

3.3

Methods of Berkeley Socket API

Berkeley Socket API provides a number of functionor methods using which the inner details of network implementation s can be used to facilitate communications. The functions provided by the Berkeley sockets API library are: 21

CHAPTER 3. BERKELEY SOCKET socket() creates a new socket of a certain socket type, identied by an integer number, and allocates system resources to it. It returns a le descriptor for the socket. socket() takes three arguments: 1. domain, which species the protocol family of the created socket. 2. type, one of: SOCK SOCK SOCK SOCK STREAM (reliable stream-oriented service or Stream Sockets) DGRAM (datagram service or Datagram Sockets) SEQPACKET (reliable sequenced packet service), or RAW (raw protocols atop the network layer).

3. protocol specifying the actual transport protocol to use. The most common are IPPROTO TCP, IPPROTO SCTP, IPPROTO UDP, IPPROTO DCCP. These protocols are specied in netinet/in.h. The value 0 may be used to select a default protocol from the selected domain and type. bind() assigns a socket to an address. When a socket is created using socket(), it is only given a protocol family, but not assigned an address. This association with an address must be performed with the bind() system call before the socket can accept connections to other hosts. bind() takes three arguments: sockfd, a descriptor representing the socket to perform the bind on. my addr, a pointer to a sockaddr structure representing the address to bind to. addrlen, a socklen t eld specifying the size of the sockaddr structure. listen() After a socket has been associated with an address, listen() prepares it for incoming connections. However, this is only necessary for the stream-oriented (connection-oriented) data modes, i.e., for socket types (SOCK STREAM, SOCK SEQPACKET). listen() requires two arguments: sockfd, a valid socket descriptor. backlog, an integer representing the number of pending connections that can be queued up at any one time. The operating system usually places a cap on this value. Once a connection is accepted, it is dequeued. connect()The connect() system call connects a socket, identied by its le descriptor, to a remote host specied by that hosts address in the argument list. Certain types of sockets are connectionless, most commonly user datagram protocol sockets. For these sockets, connect takes on a special meaning: the default target for sending and receiving data gets set to the given address, allowing the use of functions such as send() and recv() on connectionless sockets. accept() When an application is listening for stream-oriented connections from other hosts, it is notied of such events (cf. select() function) and must initialize the connection using the accept() function. The accept() function creates a new socket for each connection and removes the connection from the listen queue. It takes the following arguments: sockfd, the descriptor of the listening socket that has the connection queued. cliaddr, a pointer to a sockaddr structure to receive the clients address information. 22
Created by

Amal, Nithish, Rakesh & Vishnu

CHAPTER 3. BERKELEY SOCKET addrlen, a pointer to a socklen t location that species the size of the client address structure passed to accept(). When accept() returns, this location indicates how many bytes of the structure were actually used. The accept() function returns the new socket descriptor for the accepted connection, or -1 if an error occurs. All further communication with the remote host now occurs via this new socket. Datagram sockets do not require processing by accept() since the receiver may immediately respond to the request using the listening socket. send() and recv(), or write() and read(), or sendto() and recvfrom(), are used for sending and receiving data to/from a remote socket. close() causes the system to release resources allocated to a socket. In case of TCP, the connection is terminated. gethostbyname() and gethostbyaddr() The gethostbyname() and gethostbyaddr() functions are used to resolve host names and addresses in the domain name system or the local hosts other resolver mechanisms (e.g., /etc/hosts lookup). They return a pointer to an object of type struct hostent, which describes an Internet Protocol host. The functions take the following arguments: name species the name of the host. For example: www.wikipedia.org addr species a pointer to a struct in addr containing the address of the host. len species the length, in bytes, of addr. type species the address family type (e.g., AF INET) of the host address. The functions return a NULL pointer in case of error, in which case the external integer h errno may be checked to see whether this is a temporary failure or an invalid or unknown host. Otherwise a valid struct hostent * is returned. select() is used to pend, waiting for one or more of a provided list of sockets to be ready to read, ready to write, or that have errors. poll() is used to check on the state of a socket in a set of sockets. The set can be tested to see if any socket can be written to, read from or if an error occurred. getsockopt() is used to retrieve the current value of a particular socket option for the specied socket. setsockopt() is used to set a particular socket option for the specied socket.

3.4

Modes of Berkeley Sockets

Berkeley sockets can operate in one of two modes: blocking or non-blocking. A blocking socket will not return control until it has sent (or received) some or all data specied for the operation. It is normal for a blocking socket not to send all data. The application must check the return value to determine how many bytes have been sent or received and it must resend any data not already processed. It also may cause problems if a socket continues to listen: a program may hang as the socket waits for data that may never arrive. When using blocking sockets, special consideration should be given to accept() as it may still block after indicating readability if a client disconnects during the connection phase.
Created by

23

Amal, Nithish, Rakesh & Vishnu

CHAPTER 3. BERKELEY SOCKET On the other hand, a non-blocking socket will return whatever is in the receive buer and immediately continue. If not written correctly, programs using non-blocking sockets are particularly susceptible to race conditions due to variances in network link speed. A socket is typically set to blocking or nonblocking mode using the fcntl() or ioctl() functions.

24

Created by

Amal, Nithish, Rakesh & Vishnu

Networking in java
4.1 Network Programming and Java

Java is practically a synonym for Internet Programming. There are a number of reasons for this, not the least of which is its ability to generate secure, cross-platform, portable code. However, one of the most important reasons for Java being the premier language for network programming are the classes dened in java.net package. They provide an easy-to-use means by which programmers of all skill level can access network resources. At the core of Javas networking support is the concept of a socket. A socket identies an end point in a network.

4.2

Java.net Package

The java.net package provides a powerful and exible infrastructure for networking. Figure 4.1 shows the class hierarchy for this package.

Classes for Connection Oriented Communication


Connection Oriented communication is made possible by using TCP/IP protocol and classes that support socket based communication based on TCP/IP protocol. These 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 Javas I/O system to other programs that may reside either on the local machine or on any other machine on the Internet. One is for servers, and the other is for clients. They are: 1. ServerSocket Java has a dierent socket class that is used for crating server applications. The ServerSocket class is used to create servers that listen for local or remote client programs to connect to them on published ports. When a ServerSocket is created, it will register itself with the system as having an intrest in client connections. The constructor of ServerSocket class has the format ServerSocket(int port) throws IOException. ServerSocket has a method called accept(), which is a blocking call that will wait for a client to initiate 25

CHAPTER 4. NETWORKING IN JAVA

Figure 4.1: The java.net package

26

Created by

Amal, Nithish, Rakesh & Vishnu

CHAPTER 4. NETWORKING IN JAVA communication and then return with a normal Socket that is used for communication with client. ServerSocket class uses TCP/IP protocol for communication. 2. Socket The Socket class is for clients and is designed to connect to ServerSocket and initiate protocol exchanges. Creation of Socket object implicitly establishes a connection between client and server. The constructor of Socket class has the following formats Socket(String hostName, int port) throws UnknownHostException,IOException Socket(InetAddress ipaddress, int port) throws IOException Input and output streams associated with a Socket can be retrieved by using getInputStream() and getOutputStream().

Classes for Connection-less Communication


TCP/IP-style networking provides predictable and serialized, reliable stream of packet data. but however using TCP/IP tends to be inecient as it requires a dedicated connection and several other features like retransmission of lost data etc. Here Connection-less data communication provides an alternative. Connection-less communication is made possible by using UDP protocol and classes that can transport Datagrams from one machine to another without using a dedicated connection. Datagrams are bundles of information that are passed between machines. Java implements datagrams on top of UDP protocol by using two classes: 1. DatagramSocket DatagramSocket class has four constructor formats. DatagramSocket() throws SocketException DatagramSocket(int port) throws SocketException DatagramSocket(int port, InetAddress ipAddress) throws SocketException DatagramSocket(SocketAddress address) throws SocketException The rst creates a DatagramSocket bound to any unused port on the local computer. The second creates a DatagramSocket bound to port specied by port. The third creates a DatagramSocket bound to specied port and InetAddress while fourth constructs a DatagramSocket bound to specied SocketAddress. Two most important method dened by DatagramSocket class are send() and receive(). send() method sends packet to the port specied by packet while receive() method waits for a packet to be received from the port specied by packet. void send(DatagramPacket packet) throws IOException void receive(DatagramPacket packet) throws IOException 2. DatagramPacket Datagram Packet represents the packets which are used to send information between systems. These packets can store information as binary array. DatagramPackets constructed to send information contains the receiver address represented by InetAddress class. DatagramPacket denes several constructors. DatagramPacket(byte data[ ], int size)
Created by

27

Amal, Nithish, Rakesh & Vishnu

CHAPTER 4. NETWORKING IN JAVA DatagramPacket(byte data[ ], int oset, int size) DatagramPacket(byte data[ ], int size, InetAddress ipAddress, int port) DatagramPacket(byte data[ ], int oset, int size, InetAddress ipAddress, int port) The rst constructor species a buer that will receive data, and the size of a packet. It is used for receiving data over a DatagramSocket. The second form allows you to specify an oset into the buer at which data will be stored. The third form species a target address and port, which are used by a DatagramSocket to determine where the data in the packet will be sent. The fourth form transmits packets beginning at the specied oset into the data.

Other Important Classes in java.net package


1. InetAddress The InetAddress class represents an Internet Protocol (IP) address and can be used when creating DatagramPacket or Socket objects. The class does not have public constructor functions. Instead it supports three static methods which return one or more instances of InetAddress. The InetAddress class contains two elds namely, hostName (of type String object) and address (of type int) which are not public. The hostName eld contains the name of host and the address eld contains the 32 bit IP address, for e.g.. 140.105.16.63 (this is IPv4. This representation will be dierent for a 16 byte IPv6 address). The getLocalHost(), getByName() and getAllByName() methods must be used by applications to create a new InetAddress instance. The syntax of these methods are as folllows: public static InetAddress getLocalHost()throws UnknownHostException public static InetAddress getByName(String host)throws UnknownHostException public static InetAddress[] getAllByName(String host)throws UnknownHostException

4.3

Java.rmi Package

RMI is Remote Method Invocation. It is a mechanism that enables an object on one Java virtual machine to invoke methods on an object in another Java virtual machine. Any object that can be invoked this way must implement the Remote interface. When such an object is invoked, its arguments are marshalled and sent from the local virtual machine to the remote one, where the arguments are unmarshalled. When the method terminates, the results are marshalled from the remote machine and sent to the callers virtual machine. If the method invocation results in an exception being thrown, the exception is indicated to caller.

Classes of Java.rmi Package


1. MarshalledObject A MarshalledObject contains a byte stream with the serialized representation of an object given to its constructor. The get method returns a new copy of the original object, as deserialized from the contained byte stream. The contained object is serialized and deserialized with the same serialization semantics used for marshaling and unmarshaling parameters and return values of RMI calls. Syntax of the get() method is: public Object get()throws IOException, ClassNotFoundException 28
Created by

Amal, Nithish, Rakesh & Vishnu

CHAPTER 4. NETWORKING IN JAVA 2. Naming The Naming class provides methods for storing and obtaining references to remote objects in the remote object registry. The Naming classs methods take, as one of their arguments, a name that is a URL formatted String of the form //host:port/name where host is the host (remote or local) where the registry is located, port is the port number on which the registry accepts calls, and where name is a simple string uninterpreted by the registry. Both host and port are optional. If host is omitted, the host defaults to the local host. If port is omitted, then the port defaults to 1099, the well-known port that RMIs registry, rmiregistry, uses. The bind() method of Naming class binds the specied name to a remote object. Syntax of bind() method is as follows: public static void bind(String name, Remote obj)throws AlreadyBoundException, MalformedURLException, RemoteException 3. RMISecurityManager RMISecurityManager provides an example security manager for use by RMI applications that use downloaded code. RMIs class loader will not download any classes from remote locations if no security manager has been set. RMISecurityManager does not apply to applets, which run under the protection of their browsers security manager. RMISecurityManager class provide a public no argument constructor to produce objects.

Interfaces of Java.rmi Package


1. Remote The Remote interface serves to identify interfaces whose methods may be invoked from a non-local virtual machine. Any object that is a remote object must directly or indirectly implement this interface. Only those methods specied in a remote interface, an interface that extends java.rmi.Remote are available remotely. Implementation classes can implement any number of remote interfaces and can extend other remote implementation classes. RMI provides some convenience classes that remote object implementations can extend which facilitate remote object creation. These classes are java.rmi.server.UnicastRemoteObject and java.rmi.activation.Activatable.

4.4

Java.sql Package

JDBC is a Java-based data access technology which provides methods for querying and updating data in a database. This technology is an API for the Java programming language that denes how a client may access a database. The classes that makes up the Application Programming Interface of JDBC technology are contained in the Java.sql package. Java.sql package constitutes an API providing a framework which allows dierent drivers to be installed dynamically to access dierent data sources. Although the JDBC API is mainly geared to passing SQL statements to a database, it provides for reading and writing data from any data source with a tabular format. The reader/writer facility, available through the javax.sql.RowSet group of interfaces, can be customized to use and update data from a spread sheet, at le, or any other tabular data source.

Classes of Java.sql Package


1. DriverManager This class provides the basic services for managing a set of JDBC drivers. As part of its
Created by

29

Amal, Nithish, Rakesh & Vishnu

CHAPTER 4. NETWORKING IN JAVA initialization, the DriverManager class will attempt to load the driver classes referenced in the jdbc.drivers system property. This allows a user to customize the JDBC Drivers used by their applications. The most important method of DriverManager class is the getConnection(). It has three forms which is described below. static Connection getConnection(String url)throws SQLException static Connection getConnection(String url, Properties info)throws SQLException static Connection getConnection(String url, String user, String password)throws SQLException The getConnection() method attempts to establish a connection to the given database URL. The DriverManager attempts to select an appropriate driver from the set of registered JDBC drivers.

Interfaces of Java.sql Package


1. Connection The Connection interface describes a connection(session) with a specic database. It allows SQL statements to be executed and results to be returned within the context of a connection. The most important method provided by this interface is the createStatement(). Its Syntax is described below. Statement createStatement() The createStatement() creates a Statement object for sending SQL statements to the database. 2. ResultSet The ResultSet interface represents a table of data representing a database result set, which is usually generated by executing a statement that queries the database. A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the rst row. The next() method moves the cursor to the next row, and because it returns false when there are no more rows in the ResultSet object. The ResultSet interface provides getter methods (getBoolean, getLong, and getString) for retrieving column values from the current row. Values can be retrieved using either the index number(integer value) of the column or the name of the column(String). 3. Statement The Statement interface describes an object used for executing a static SQL statement and returning the results it produces. The most important methods of Statement interface are. ResultSet executeQuery(String sql)throws SQLException int executeUpdate(String sql)throws SQLException The executeQuery() methods executes the given SQL statement, which returns a single ResultSet object while executeUpdate() method Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement.

30

Created by

Amal, Nithish, Rakesh & Vishnu

Java Server Pages


5.1 Introduction to JSP

JavaServer Pages (JSP) is a technology that helps software developers create dynamically generated web pages based on HTML, XML, or other document types. JSP is a server side script, but it uses the Java programming language. To deploy and run JavaServer Pages, a compatible web server with a servlet container, such as Apache Tomcat, is required. A discussion about JSP would be incomplete without an overview about Java servlets because JSP can be viewed as a high-level abstraction of Java servlets. A Servlet is a Java-based server-side web technology. Technically speaking, a Servlet is a Java class that conforms to the Java Servlet API, a protocol by which a Java class may respond to requests. Servlets could in principle communicate over any clientserver protocol. JSPs are translated into servlets at runtime. Each JSPs servlet is cached and re-used until the original JSP is modied. JSP allows Java code to be embedded within html code in a JSP page so that certain predened actions can be interleaved with static web markup content, with the resulting page being compiled and executed on the server to deliver a document. The compiled pages, as well as any dependent Java libraries, use Java byte-code rather than a native software format. Like any other Java program, they must be executed within a Java virtual machine (JVM) that integrates with the servers host operating system to provide an abstract platform-neutral environment. JSP pages are usually used to deliver HTML and XML documents, but through the use of OutputStream, they can deliver other types of data as well.

5.2

Advantages of JSP

A java server page is a template for web page that uses java code to generate HTML documents dynamically. JSPs are run in sever side components known as JSP containers, which translates them into equivalent Java Servlets. For this reason servlets and JSP pages are intimately related. JSP pages have all advantages of servlets. 1. They have better performance and scalability than ordinary CGI scripts because they are persistent in memory and multithreaded. 31

CHAPTER 5. JAVA SERVER PAGES 2. No special client setup is required. 3. They have built in support for HTTP sessions, which makes application programming possible. 4. They have full access to java technology without limitations of client side applets.

5.3

How JSP Works

Figure 5.1: Architecture of Java Server Pages

A JSP page exist in 3 forms. 1. JSP source code This is the version the developer actually writes. it consist of a text le with .jsp extension, and contains a mix of HTML template code, Java language statements, and JSP directives and actions that describe how to generate a Web page to service a particular request. 2. Java Source Code The JSP container translates the JSP source code into the source code for an equivalent Java servlet as needed. This source code os typically saved in a work area and is often helpful for debugging. 3. Compiled Java class Like any other Java class, the generated servlet code is compiled into byte codes in a .class le, ready to be loaded and executed. The JSP container manages each of these forms of JSP page automatically, based on the timestamp of each le. In response to an HTTP request, the container checks to see if the .jsp source has been modied since the .java source was last compiled. If so, the container retranslates the JSP source code into Java source and recompiles it. When a request for JSP page is made, the container rst determines the name of the class corresponding to .jsp le. If class doesnt exits or is older than .jsp le, then the container creates java source code for equivalent servlet and recompiles it. Then the container loads the servlet class and creates an instance. Finally the container dispatches a thread to handle the current HTTP request in loaded instance. 32
Created by

Amal, Nithish, Rakesh & Vishnu

CHAPTER 5. JAVA SERVER PAGES

5.4

Components of a JSP page

A .jsp le can contain JSP elements, xed template data, or any combination of the two. JSP elements are instructions to the JSP container about what code to generate and how it should operate. these elements have specic start and end tags that identify them to the JSP compiler. Template data is everything else that is not recognized by the JSP container. Template data is passes through unmodied, so the HTMl that is ultimately generated contains the template data exactly as it was coded. There are three type of JSP elements Directives Scripting elements, including expressions, scriptlets, and declarations Actions

Directives
Directives are instructions to JSP container that describes what code should be generated. They have general form < %@ directive name[attribute = value attribute = value ...]% > Three standard directives are available in all compliant JSP environments: page include taglib The page Directive The page directive is used to specify attributes for the JSP page as a whole. It has the following syntax: < %@ page [attribute = value attribute = value ...] % > Some of the important attributes of page directive s are language, extends, import, session and errorPage The include Directive The include directive merges the contents of another le at translation time into the .jsp source input stream, much like a #include C preprocessor directive. The syntax is < %@ include f ile = f ilename % > where lename is an absolute or relative pathname interpreted according to the current servlet context. The taglib Directive The taglib directive makes custom actions available in the current page through the use of a tag library. The syntax of the directive is < %@ taglib uri = tagLibraryU RI pref ix = tagP ref ix % > where tagLibrary is the URL of a Tag Library Descriptor and URI tagPrex is a unique prex used to identify custom tags used later in the page.
Created by

33

Amal, Nithish, Rakesh & Vishnu

CHAPTER 5. JAVA SERVER PAGES

Scripting elements
Expressions JSP provides a simple means for accessing the value of a Java variable or other expression and merging that value with the HTML in the page. The syntax is < % = exp % > where exp is any valid Java expression. The expression can have any data value, as long as it can be converted to a string. This conversion is usually done simply by generating an out.print() statement. Scriptlets A scriptlet is a set of one or more Java language statements intended to be used to process an HTTP request. The syntax of a scriptlet is < % statement; [statement; ...]% > The JSP compiler simply includes the contents of scriptlet verbatim in the body of the jspService() method. A JSP page may contain any number of scriptlets. If multiple scriptlets exist, they are each appended to the jspService() method in the order in which they are coded. This being the case, a scriptlet may contain an open curly brace that is closed in another scriptlet. Declarations Like scriptlets, declarations contain Java language statements, but with one big dierence: scriptlet code becomes part of the jspService() method, whereas declaration code is incorporated into the generated source le outside the jspService() method. The syntax of a declaration section is < %! statement; [statement; ...]% >

Actions
Actions are high-level JSP elements that create, modify, or use other objects. Unlike directives and scripting elements, actions are coded using strict XML syntax < tagname [attr = valueattr = value ...] > ... < /tag name > or, if the action has no body, an abbreviated form: < tagname [attr = valueattr = value ...] / > XML syntax requires the following: Every tag must have matching end tag or use the short form / previously shown Attribute values must be placed in quotes Tags must be properly nested. Seven standard actions are available in all JSP compliant environments.

34

Created by

Amal, Nithish, Rakesh & Vishnu

Extended Markup Language


6.1 What is XML

Extensible Markup Language or shortly XML is simply a set of rules used to impose structure and syntax on plain text. XML allows hierarchical and structured data to be represented with ease. XML is a subset of Standard General Markup Language (SGML) and is dened in XML 1.0 Specication produced by the W3C. XML denes a set of rules for encoding documents in a format that is both human-readable and machine-readable. It allows creating documents that are platform independent This property of XML allows it to be used to exchange data over a network. XML achieves it structuring using markups or tags which are placed over plain data. The tags can be nested indenitely allowing XML to represent highly complex and hierarchical data with ease. Similar to HTML documents, XML documents can be created in a text editor, such as Notepad which can be then saved in .xml extension. Unlike HTML which have predetermined tags, XMLs tags are user dened and hence XML is highly extensible. XML documents are processed by XML parsers and the data is passed to the applications interested in using them.

6.2

Structure of XML Document.

An XML document consists of three parts, in the order given: 1. XML declaration which species that the document is an XML document. It is technically optional, but recommended in most normal cases. 2. A document type declaration that refers to a DTD (which is optional, but required if you want validation). 3. A body or document instance (which is required).

6.3

Components of an XML Document

An XML document consists of several components, such as declaration statements, elements, tags, and attributes. The following sections discuss these components in detail. 35

CHAPTER 6. EXTENDED MARKUP LANGUAGE

XML Declaration Statement


The XML declaration statement is included in the beginning of an XML document. It is used to indicate that the specied document is an XML document. The XML declaration statement includes a keyword, xml, preceded by a question mark (?). This statement includes the XML specication to which the XML document adheres. For example, if the XML document that you create is based on XML Specication 1.0, then the XML declaration statement would be as shown here: <?xml version = 1.0? >

Markup Syntax
Components, such as declaration statements or markup tags, dene the syntax for creating an XML document. The syntax used to create an XML document is called markup syntax. The markup syntax is used to dene the structure of the data in the document. The markup syntax includes all tags, DOCTYPE declaration statements, comments, DTDs, and character references.

Document Type Denitions


XML allows creation of custom tags. However, when a structured document is created, the structure needs to be conveyed to the users who use the XML document. This can be done using Document Type Denitions (DTDs). A DTD is a vocabulary that denes the structure and elements in an XML document. An XML document that has a DTD attached to it is called a valid XML document. This implies that a valid XML document is both syntactically correct and conforms to the rules of vocabulary as described in a DTD. To use a DTD with an XML document, the DTD needs to be associated with the XML document . To do this, the DOCTYPE declaration statement is included in the beginning of the XML document.

The Doctype Declaration Statement


The Doctype declaration statement includes the keyword DOCTYPE. In addition, the Doctype declaration statement might include the markup declaration statement as a subset. The markup declaration statements, which are included as a subset of the Doctype declaration statement, are called internal DTD subset. The syntax of the Doctype declaration statement is as shown: <!DOCT Y P E name [markup statements] > Similarly, an external DTD can also be included in the XML document. To do this, the source and path of the external DTD is include in the doctype declaration statement. The path of a DTD is the URL of the .dtd le. The DTD statement also includes a keyword, which can be either SYSTEM or PUBLIC. The SYSTEM keyword denotes that the markup declaration statements are directly included in the .dtd le present at the specied URL. The PUBLIC keyword denotes that the DTD to be included is a well-known vocabulary in the form of a local copy of the .dtd or .dtd le placed in a database server.

XML Entities
In addition to the markup syntax, an XML document consists of the content or data to be displayed. The content of the XML le is the data enclosed within tags. The data stored in an XML document is in the form of text, and it is commonly called an XML entity or a text entity. 36
Created by

Amal, Nithish, Rakesh & Vishnu

CHAPTER 6. EXTENDED MARKUP LANGUAGE The text entity is used to store the text in the form of character values as dened in the Unicode Character Set. The following example shows the text data in an XML document: < Employee N ame > John Smith < /Employee N ame >

Comments
Another important component of an XML document is comment entries. Comments allow you to include instructions or notes in an XML document. These comments help you to provide any metadata about the document to the users of the document. Any data that is not part of the main content or the markup syntax can be included in comment entries The syntax is as shown: <! comment >

Elements
The building blocks of any XML document are its elements. Elements or tags are containers that contain XML data, such as text, text references, entities, and so on. You can also include elements within another element. This implies that you can have nested elements. The content within an element is called the element content. It is essential that you enclose all XML data within elements. All elements include starting and ending tags. However, if an elements has no content, an empty element can be created. Empty elements can be written in an abbreviated form. the syntax of an empty element is < Element N ame/ >

Attributes
Attributes are used to specify properties of an element. An attribute has a value associated with it. In the preceding code, the keyword color is an attribute of the element apple, and the value assigned to the color attribute is red. Attributes allow you to provide additional information in an XML document. The value of an attribute is assigned to it by using the equal sign (=), and it is enclosed within double quotes () as shown. < Element N ame Attribute N ame1 = value [Attribute; N ame2 = value]... > All the attributes that can be declare for an element can included in a DTD. A DTD contains the ATTLIST tag that includes the attribute declaration statement for each attribute. You can include multiple attribute denitions in one ATTLIST tag. However, to avoid confusion, it is advisable to include a dierent AATLIST tag for each attribute. The syntax for the ATTLIST tag is as shown: <!AT T LIST element name attribute name value >

6.4

Syntax rules of XML

1. All XML Elements must have an opening and closing tags. Empty elements can have short hand notation.
Created by

37

Amal, Nithish, Rakesh & Vishnu

CHAPTER 6. EXTENDED MARKUP LANGUAGE 2. All tags must be properly nested. < a >< b > ... < /a >< /b > is invalid. It must be

< a >< b > ... < /b >< /a > 3. XML tags are highly case sensitive. 4. All XML documents must have a root element. All other elements must be nested within the root element. 5. Attribute values must always be quoted.

6.5

Advantages of using XML

XML because of its SGML foundation, is exible enough to work for any situation that requires the formatting of structured data. Any information that can be stored in a spreadsheet or database type structure can be stored within an XML document. XML document have very strict sidelines that must be followed in order for them to be read by the variety of parsing and validating software available for use with XML documents on the internet. Documents that meet the requirements are termed well-formed, having followed all of the rules for creating XML documents and applications. XML is highly extensibility and has a universal format. So it is widely used for data exchange between applications and networks. XML allows creation of custom tags based on the requirements of a document. Therefore, they can be used as a vocabulary for all related documents. The simplicity oered by XML allows it to be easy to understood and used. The organization abilities XML allows structuring even complex data and seamless building of platform by segmenting the design process. Separation of data and formatting rules simplies the development process. XML is an international standard. This implies that an XML document can be processed by all application s with ease. Highly extensible property of XML in form of creating DTDs and personalized tags allows it be used for all types of applications with ease. XML allows structured data transportation and handling easy.

38

Created by

Amal, Nithish, Rakesh & Vishnu

Applets
7.1 Java Applet

Applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part of a Web document. Applet is a client side technology as far as networking is concerned. After an applet arrives on the client, it has limited access to resources, so that it can produce an arbitrary multimedia user interface and run complex computations without introducing the risk of viruses or breaching data integrity. Java Applets can provide web applications with interactive features that cannot be provided by HTML. Since Javas bytecode is platform-independent, Java applets can be executed by browsers running under many platforms, including Windows, Unix, Mac OS, and Linux. When a Java technology-enabled web browser processes a page that contains an applet, the applets code is transferred to the clients system and executed by the browsers Java Virtual Machine (JVM). An HTML page references an applet either via the deprecated < AP P LET >

7.2

Capabilities of an Applet

Applets can capture mouse input and also have controls like buttons or check boxes. In response to the user action an applet can change the provided graphic content. This makes applets well suitable for demonstration, visualization and teaching. Applets can also play media in formats that are not natively supported by the browser. HTML pages may embed parameters that are passed to the applet. Hence the same applet may appear dierently depending on the parameters that were passed. Java applets are executed in a sandbox by most web browsers, preventing them from accessing local data like clipboard or le system. The code of the applet is downloaded from a web server and the browser either embeds the applet into a web page or opens a new window showing the applets user interface. A Java applet extends the class java.applet.Applet, or in the case of a Swing applet, javax.swing.JApplet. The class must override methods from the applet class to set up a user interface inside itself (Applet) is a descendant of Panel which is a descendant of Container. As applet inherits from container, it has largely the same user interface possibilities as an ordinary Java application, including regions with user specic visualization. 39

CHAPTER 7. APPLETS

7.3

Advantages

A Java applet has the following advantages: It is simple to make it work on Linux, Microsoft Windows and OS X i.e. to make it cross platform. Applets are supported by most web browsers. The same applet can work on all installed versions of Java at the same time, rather than just the latest plug-in version only. Most web browsers cache applets so will be quick to load when returning to a web page. Applets also improve with use: after a rst applet is run, the JVM is already running and starts quickly (the JVM will need to restart each time the browser starts afresh). It can move the work from the server to the client, making a web solution more scalable with the number of users/clients. If a standalone program (like Google Earth) talks to a web server, that server normally needs to support all prior versions for users which have not kept their client software updated. In contrast, a properly congured browser loads (and caches) the latest applet version, so there is no need to support legacy versions. The applet naturally supports the changing user state, such as gure positions on the chessboard. Developers can develop and debug an applet direct simply by creating a main routine (either in the applets class or in a separate class) and calling init() and start() on the applet, thus allowing for development in their favorite Java SE development environment. All one has to do after that is re-test the applet in the AppletViewer program or a web browser to ensure it conforms to security restrictions. An untrusted applet has no access to the local machine and can only access the server it came from. This makes such an applet much safer to run than a standalone executable that it could replace. However, a signed applet can have full access to the machine it is running on if the user agrees. Java applets are fast - and can even have similar performance to native installed software.

7.4

Applet Architecture

An applet is a window-based program. applets are event driven. An applet resembles a set of interrupt service routines. An applet waits until an event occurs. The Abstract Window Toolkit (AWT) noties the applet about an event by calling an event handler that has been provided by the applet. Once this happens, the applet must take appropriate action and then quickly return control to the AWT. An applet must perform specic actions in response to events and then return control to the AWT run-time system. The user initiates interaction with an applet. the user interacts with the applet as and when they wants. These interactions are sent to the applet as events to which the applet must respond. The basic mechanism by which the browser or applet viewer interfaces to the applet and controls its execution are Four methodsinit( ), start( ), stop( ), and destroy( )dened by Applet class in Java.applet package and paint( ) dened by the AWT Component class. These methods are described below. 40
Created by

Amal, Nithish, Rakesh & Vishnu

CHAPTER 7. APPLETS

init( )
The init( ) method is the rst method to be called. This is where you should initialize variables. This method is called only once during the run time of your applet.

start( )
The start( ) method is called after init( ). It is also called to restart an applet after it has been stopped. Whereas init( ) is called oncethe rst time an applet is loadedstart( ) is called each time an applets HTML document is displayed onscreen. So, if a user leaves a web page and comes back, the applet resumes execution at start( ).

stop( )
The stop( ) method is called when a web browser leaves the HTML document containing the appletwhen it goes to another page, for example. When stop( ) is called, the applet is probably running. You should use stop( ) to suspend threads that dont need to run when the applet is not visible. You can restart them when start( ) is called if the user returns to the page.

destroy( )
The destroy( ) method is called when the environment determines that your applet needs to be removed completely from memory. At this point, you should free up any resources the applet may be using. The stop( ) method is always called before destroy( ).

paint( )
The paint( ) method is called each time your applets output must be redrawn. This situation can occur for several reasons. For example, the window in which the applet is running may be overwritten by another window and then uncovered. Or the applet window may be minimized and then restored. paint( ) is also called when the applet begins execution. Whatever the cause, whenever the applet must redraw its output, paint( ) is called. The paint( ) method has one parameter of type Graphics. This parameter will contain the graphics context, which describes the graphics environment in which the applet is running. This context is used whenever output to the applet is required.

7.5

The HTML APPLET Tag

The APPLET tag is used to start an applet from both an HTML document and from an applet viewer. Web browsers allow many applets on a single page. The syntax for the standard APPLET tag is shown here. Square bracketed items are optional.
Created by

41

Amal, Nithish, Rakesh & Vishnu

CHAPTER 7. APPLETS

< AP P LET [CODEBASE = codebaseURL] CODE = appletFile [ALT = alternateText] [NAME = appletInstanceName] WIDTH = pixels HEIGHT = pixels [ALIGN = alignment] [VSPACE = pixels] [HSPACE = pixels] > [< PARAM NAME = AttributeName VALUE = AttributeValue>] [< PARAM NAME = AttributeName2 VALUE = AttributeValue>] ... [HTML Displayed in the absence of Java] </APPLET> CODEBASE optional attribute that species the base URL of the applet code. CODE CODE is a required attribute that gives the name of the le containing your applets compiled .class le. ALT The ALT tag is an optional attribute used to specify a short text message that should be displayed if the browser understands the APPLET tag but cant currently run Java applets. NAME NAME is an optional attribute used to specify a name for the applet instance. Applets must be named in order for other applets on the same page to nd them by name and communicate with them. ALIGN ALIGN is an optional attribute that species the alignment of the applet. VSPACE AND HSPACE These attributes are optional. VSPACE species the space, in pixels, above and below the applet. HSPACE species the space, in pixels, on each side of the applet. PARAM NAME AND VALUE The PARAM tag allows you to specify applet- specic arguments in an HTML page. Applets access their attributes with the getParameter( ) method.

42

Created by

Amal, Nithish, Rakesh & Vishnu

Part III

Experiments

43

Connecting Two Computers


Description
This experiment requires connecting two computers using a Ethernet cable or LAN cable so that data can be shared between them. This is primarily done so that programs which illustrates networking technologies can be illustrated by running server program (a peer program) in one machine and client program (another peer) in other machine.

Steps to be followed to connect two computers


1. Connect both computers by inserting the Ethernet cables either ends to the RJ-45 port of the computers. 2. If the computer is using windows operating System , then do following steps a) Open Network and Sharing Center. b) Click on Local Area Connection. This will open a window named Local Area Connection Status. c) In this newly opened Window, Click on properties.This will open Local Area Connection Properties window. d) In the list Appearing in the Local Area Connection Properties Window, select Internet Protocol Version 4 and click on properties. e) In the newly opened window select Use the following IP address and ll in the following details IP address= The IP Address we intended to give the machine Subnet Mask =255.255.255.0 Default Gateway=The IP address of the other machine f) Click OK on Internet Protocol Version 4 Properties window g) Click OK on the window Local Area Connection Properties h) Click close on the window Local Area Connection Status 45

CHAPTER 8. CONNECTING TWO COMPUTERS i) The current computer is now connected. 3. If the computer is using Linux based operating System , then do following steps a) From the Control Center open Network connections. b) Click on Wired tab and select the ethernet connection representing the currently connected ethernet cable. c) Click on Edit button. d) in the newly opened window select the tab IPv4 settings tab. e) Select the Method to Manual. f) Click on Add button and ll in following details. Address= The IP Address we intended to give the machine Net Mask =255.255.255.0 Gateway=The IP address of the other machine g) Click Save h) Close the Network Connection Window i) The current computer is now connected. 4. The connection can now be veried by using ping command by giving other machines IP address as argument. Note: In setting up the connection we have used 7.7.7.7 as machine 1s IP address and 7.7.7.6 as machine 2s IP address.

46

Created by

Amal, Nithish, Rakesh & Vishnu

CHAPTER 8. CONNECTING TWO COMPUTERS

Output

Figure 8.1: Output Screen

Result
Two Computers are connected using ethernet cable and connection is checked using ping command.

Created by

47

Amal, Nithish, Rakesh & Vishnu

Berkeley Socket
Description
Here, in this experiment, we have created a client program which communicate with server program. The server reverses the string sent by client and sends it back.

Algorithm
Algorithm BerkeleyServer begin Step Step Step Step Step Step Step end Algorithm BerkeleyClient begin Step Step Step Step Step Step Step end 1: 2: 3: 4: 5: 6: 7: Start Client Connect to server Read a message from user Send the message to the server Read a message from server Print the message Stop 1: 2: 3: 4: 5: 6: 7: Start Server Wait for a connect request from the client Accept the connection request Read a message from client Find reverse of message and store it on reverse mesage Send the reverse message back to client Goto Step 2

49

CHAPTER 9. BERKELEY SOCKET

Program
berkeleyServer.c
# include < stdio .h > # include < arpa / inet .h > # include < string .h > void reverse ( char * str , int l ) ; int main () { char s [100]; int serversockfd ,l , newserversockfd , clength ; struct sockaddr_in clientaddress , serveraddress ; serveraddress . sin_family = AF_INET ; serveraddress . sin_addr . s_addr = inet_addr ( " 127.0.0.1 " ) ; serveraddress . sin_port = htons (3000) ; serversockfd = socket ( AF_INET , SOCK_STREAM ,0) ; bind ( serversockfd ,( struct sockaddr *) & serveraddress , sizeof ( serveraddress ) ) ; listen ( serversockfd ,5) ; clength = sizeof ( clientaddress ) ; newserversockfd = accept ( serversockfd ,( struct sockaddr *) & clientaddress ,& clength ) ; while (1) { read ( newserversockfd ,s ,100) ; printf ( " Recieved : % s \ n " ,s ) ; l = strlen ( s ) ; reverse (s , l ) ; write ( newserversockfd ,s , l +1) ; } close ( newserversockfd ) ; close ( serversockfd ) ; return 0; } void reverse ( char * str , int l ) { int i ; char c ; for ( i =0; i < l /2; i ++) { c = str [ i ]; str [ i ]= str [l -i -1]; str [l -i -1]= c ; } }

berkeleyClient.c
# include < stdio .h > # include < arpa / inet .h > # include < string .h > int main () { char str [100] , str1 [100]; int clientsockfd , l ; struct sockaddr_in serveraddress ; serveraddress . sin_port = htons (3000) ; serveraddress . sin_addr . s_addr = inet_addr ( " 127.0.0.1 " ) ; serveraddress . sin_family = AF_INET ; clientsockfd = socket ( AF_INET , SOCK_STREAM , 0 ) ; if ( connect ( clientsockfd ,( struct sockaddr *) & serveraddress , sizeof ( serveraddress ) ) <0) { printf ( " Can not Connect " ) ; } printf ( " Enter the String : " ) ;

50

Created by

Amal, Nithish, Rakesh & Vishnu

CHAPTER 9. BERKELEY SOCKET


scanf ( " % s " , str ) ; l = strlen ( str ) ; write ( clientsockfd , str , l +1) ; read ( clientsockfd , str1 , l +1) ; printf ( " Reversed String is : % s \ n " , str1 ) ; close ( clientsockfd ) ; return 0; }

Created by

51

Amal, Nithish, Rakesh & Vishnu

CHAPTER 9. BERKELEY SOCKET

Output

Figure 9.1: Output Screen

52

Created by

Amal, Nithish, Rakesh & Vishnu

CHAPTER 9. BERKELEY SOCKET

Output

Figure 9.2: Output Screen

Result
The Program is executed successfully and the output is obtained.

Created by

53

Amal, Nithish, Rakesh & Vishnu

10

Echo Server
Description
A server program that supports Echo Protocol is generally called as an Echo Server. In this protocol the server sends back an identical copy of the data it received back to the client that send them as soon as it is received. In the following sections of this chapter, we describe an implementation of a server that implements Echo Protocol. The implementation contains a server capable of accepting connection requests of multiple clients at same time. After connecting, server waits until it receives data from its clients. The received data(a text string in the implementation) is sent back to the respective clients as soon as it is received. Each client receives back the data it sends to the server.

Algorithm
Algorithm EchoServer begin Step Step Step Step Step Step Step Step Step end Algorithm EchoClient begin Step 1: Start Client Step 2: Connect to server Step 3: Read a message from user 55 1: 2: 3: 4: 5: 6: 7: 8: 9: Start Server Do Step 3 and 6 in parallel Wait for a connect request from the client Accept the connection request Goto Step 3 For each connected client, do Step 7 to 8 repeatedly Read a message from client Send the same message back to client Stop

CHAPTER 10. ECHO SERVER Step Step Step Step Step end 4: 5: 6: 7: 8: Send the message to the server Read a message from server Print the message If message is not bye Goto Step 3 Stop

Program
import import import import java . awt . event .*; java . awt .*; java . net .*; java . io .*;

public class EchoServer { private ServerSocket server ; public EchoServer ( int pnum ) { try { server = new ServerSocket ( pnum ) ; } catch ( Exception e ) { System . out . println ( " Error " ) ; } } public void serve () { try { while ( true ) { System . out . println ( " Waiting for client " ) ; Socket ct = server . accept () ; System . out . println ( " Client connected " ) ; BufferedReader b = new BufferedReader ( new InputStreamReader ( ct . getInputStream () ) ) ; PrintWriter p = new PrintWriter ( ct . getOutputStream () , true ) ; // p . println (" Welcome to Server Enter bye to close ") ; String l ; do { l = b . readLine () ; System . out . println ( l ) ; if ( l != null ) p . println ( " Server : " + l ) ; } while (! l . trim () . equals ( " bye " ) ) ; ct . close () ; System . out . println ( " Client disconnected " ) ; } } catch ( Exception er ) { System . out . println ( " Caught " + er ) ; } } public static void main ( String args []) {

56

Created by

Amal, Nithish, Rakesh & Vishnu

CHAPTER 10. ECHO SERVER


EchoServer es = new EchoServer (9999) ; es . serve () ; } } class myframe extends Frame implements ActionListener { String msg = null ; TextArea text = null ; TextField text1 = null ; Button b = null ; Panel p = null ; client c ; public myframe () { init () ; } void init () { msg = " " ; addWindowListener ( new WindowAdapter () { public void windowClosing ( WindowEvent e ) { System . exit (0) ;}}) ; setLayout ( new BorderLayout () ) ; // p = new Panel () ; // add (p , BorderLayout . SOUTH ) ; // setLayout ( new BorderLayout () ) ; setTitle ( " Client " ) ; setSize (300 ,300) ; setVisible ( true ) ; text = new TextArea ( " " ) ; text . setSize (180 ,50) ; text . setEditable ( false ) ; add ( text , BorderLayout . NORTH ) ; text1 = new TextField (12) ; text1 . setSize (100 ,100) ; add ( text1 , BorderLayout . CENTER ) ; b = new Button ( " Send " ) ; b . addActionListener ( this ) ; b . setSize (100 ,100) ; add (b , BorderLayout . SOUTH ) ; } public void actionPerformed ( ActionEvent ae ) { String snd = text1 . getText () ; msg = c . send ( snd ) + " \ nClient : " + snd + " \ n " + msg ; text . setText (( msg ) ) ; text1 . setText (( " " ) ) ; repaint () ; } public void paint ( Graphics g ) { g . drawString ( msg ,300 ,300) ; } public static void main ( String args []) { myframe f = new myframe () ; f . c = new client () ; } } class client { Socket cs = null ; BufferedReader br = null ; PrintWriter pw = null ; client () { try { cs = new Socket ( " 127.0.0.1 " ,9999) ; br = new BufferedReader ( new InputStreamReader ( cs . getInputStream () ) ) ; pw = new PrintWriter ( cs . getOutputStream () , true ) ; } catch ( Exception e ) {

Created by

57

Amal, Nithish, Rakesh & Vishnu

CHAPTER 10. ECHO SERVER


System . out . println ( " " ) ; } } String send ( String l ) { try { pw . println ( l ) ; if ( l . trim () . equals ( " bye " ) ) { cs . close () ; System . exit (0) ; } l = br . readLine () ; } catch ( Exception e ) { } return l ; } }

58

Created by

Amal, Nithish, Rakesh & Vishnu

CHAPTER 10. ECHO SERVER

Output

Figure 10.1: Output Screen

Result
The Program is executed successfully and the output is obtained.

Created by

59

Amal, Nithish, Rakesh & Vishnu

11

Chatting
Description
Chatting may be refer to any kind of communication that oers a real-time direct transmission of text-based messages from sender to receiver. A chatting system consist of a central server called chat server and many clients that connect to the server. The server addresses each clients by some predened method. Direct communication is only allowed between server and client. In this system a client sends a packet containing the recipient (another client) address and message content to the server. The server unpacks this packet and identies the recipient of the message. The message along with the senders address is then forwarded to the intended recipient. In the following section of this chapter, we describe an implementation of a chatting system consisting of a chat server which is capable of serving multiple clients at same time. A general implementation of a client is also described.

Algorithm
Algorithm ChatServer begin Step 1:Start the server Step 2:Do Step 3 and 7 in parallel Step 3:Wait for connect request from client Step 4:If maximum client capacity has not reached accept the client connection Step 5:Read the name of the client Step 6:Goto Step 3 Step 7:For all connected clients do steps 8 to 10 repeatedly Step 8:Read data from client Step 9:Separate client name and message from data Step 10:Send message to the client with name client name Step 11:Stop end Algorithm ChatClient begin 61

CHAPTER 11. CHATTING Step Step Step Step Step Step Step Step Step Step Step Step end 1: Start Client 2: Connect to server 3: Send name of the client to the server 4: Do Step 4 and 8 in parallel 5: Wait for a message from Server 6: Print the message 7: Goto Step 5 8: Read the client name to which message is to be sent from user 9: Read the message to be sent from user 10: Sent the client name and message to server 11: If message is not bye Goto Step 8 12: Stop

Program
import import import import java . net .*; java . awt .*; java . io .*; java . awt . event .*;

class server implements Runnable { ServerSocket s = null ; Socket c []= null ; BufferedReader in []= null ; PrintWriter out []= null ; Thread t []= null ; int number_client ; String message = null ; String send ( String message ) { for ( int i =0; i < number_client ; i ++) { out [ i ]. println ( message ) ; } return message ; } void recieve () { } public void run () { int client_no = Integer . parseInt ( Thread . currentThread () . getName () ) ; do { try { String s = in [ client_no ]. readLine () ; if ( s . trim () . equals ( " bye " ) ) break ; s = " Client " + client_no + " : " + s ; send ( s ) ; System . out . println ( s ) ; // } catch ( Exception e ) { System . out . println ( " Error " ) ; break ; } } while ( true ) ; System . out . println ( " Client " + client_no + " disconnected " ) ; } public server () { int MAX = number_client =20;

62

Created by

Amal, Nithish, Rakesh & Vishnu

CHAPTER 11. CHATTING


try { s = new ServerSocket (768) ; c = new Socket [ number_client ]; in = new BufferedReader [ number_client ]; out = new PrintWriter [ number_client ]; t = new Thread [ number_client ]; number_client =0; for ( int i =0; i < MAX ; i ++) { c [ i ]= s . accept () ; number_client ++; in [ i ]= new BufferedReader ( new InputStreamReader ( c [ i ]. getInputStream () ) ) ; out [ i ]= new PrintWriter ( c [ i ]. getOutputStream () , true ) ; t [ i ]= new Thread ( this , " " + i ) ; t [ i ]. start () ; } } catch ( Exception e ) { System . out . println ( e ) ; } } public static void main ( String a []) { server s = new server () ; } } class client extends Frame implements ActionListener { Socket c = null ; BufferedReader in = null ; PrintWriter out = null ; Button b = null ; TextArea display = null ; TextField t = null ; String msg = " " ; public client () { try { setTitle ( " Client " ) ; c = new Socket ( " localhost " ,768) ; setSize (200 ,300) ; setVisible ( true ) ; display = new TextArea () ; display . setEditable ( false ) ; t = new TextField (10) ; t . setEditable ( true ) ; b = new Button ( " Send " ) ; setLayout ( new BorderLayout () ) ; add ( display , BorderLayout . NORTH ) ; add (t , BorderLayout . CENTER ) ; add (b , BorderLayout . SOUTH ) ; addWindowListener ( new WindowAdapter () { public void windowClosing ( WindowEvent e ) { System . exit (0) ;}}) ; b . addActionListener ( this ) ; } catch ( Exception e ) { System . out . println ( e ) ; } } public void actionPerformed ( ActionEvent ae ) { out . println ( t . getText () ) ; if ( t . getText () . trim () . equals ( " bye " ) ) System . exit (0) ;

Created by

63

Amal, Nithish, Rakesh & Vishnu

CHAPTER 11. CHATTING


t . setText ( " " ) ; } public static void main ( String args []) { client c1 = new client () ; try { c1 . in = new BufferedReader ( new InputStreamReader ( c1 . c . getInputStream () ) ) ; c1 . out = new PrintWriter ( c1 . c . getOutputStream () , true ) ; } catch ( Exception e ) { System . out . println ( e ) ; } String s = null ; do { try { s = c1 . in . readLine () ; c1 . msg = s + " \ n " + c1 . msg ; c1 . display . setText ( c1 . msg ) ; } catch ( Exception e ) { System . out . println ( e ) ; } } while (! s . trim () . equals ( " bye " ) ) ; } }

64

Created by

Amal, Nithish, Rakesh & Vishnu

CHAPTER 11. CHATTING

Output

Figure 11.1: Output Screen

Result
The Program is executed successfully and the output is obtained.

Created by

65

Amal, Nithish, Rakesh & Vishnu

12

File Server
Description
Downloading means to receive data to a local system from a remote system. A server program that allows connected clients to download les which is stored in its local storage is called a File Server. A le server may have ability to serve multiple clients. In the following sections of this chapter, we describe an implementation of File server which can serve multiple clients at same time. The client ones connected can send the name of a required le to the server. If the le is in the local storage of the server, the server asks for the name in which the le is to be save in the clients storage. Ones the name is received, the server initiates a le transfer with the client. At the end of the transfer, client receives an identical copy of the le in the server. Thus the client downloads the le.

Algorithm
Algorithm FileServer begin Step Step Step Step Step Step Step Step Step Step 1:Start the server 2:Do Step 3 and 6 in parallel 3:Wait for connect request from client 4:If maximum client capacity has not reached accept the client connection 5:Goto step 3 6:For all connected clients do steps 7 to 9 repeatedly 7:Read lename from client 8:Read the data in the le 9:Send the data to the client 10:Stop

end Algorithm FileClient begin Step 1: Start Client Step 2: Connect to server 67

CHAPTER 12. FILE SERVER Step 3: Read the name of the le to be downloaded from user into a variable dw le name Step 3: If dw le name is bye Goto Step 12 Step 5: Read the name in which the le is to be saved from user into a variable sav name Step 4: Send dw le name to the server Step 6: Create a new le with name sav name Step 5: Read the data coming from server Step 7: Write this data to the opened le Step 5: Save the le Step 8: Goto Step 3 Step 12: Stop end

Program
import import import import java . awt . event .*; java . awt .*; java . net .*; java . io .*;

class fileserver { private ServerSocket server ; public fileserver ( int pnum ) { try { server = new ServerSocket ( pnum ) ; } catch ( Exception e ) { System . out . println ( " Error " ) ; } } public void serve () { try { while ( true ) { System . out . println ( " Waiting for client " ) ; Socket ct = server . accept () ; System . out . println ( " Client connected Welcome to Server " ) ; BufferedReader b = new BufferedReader ( new InputStreamReader ( ct . getInputStream () ) ) ; PrintStream p = new PrintStream ( ct . getOutputStream () , true ) ; FileInputStream f = null ; // p . println (" Welcome to Server Enter bye to close ") ; String l ; l = b . readLine () ; System . out . println ( " Client requesting file " + l + " " ) ; f = new FileInputStream ( l ) ; int i ; do { i = f . read () ; p . write ( i ) ; } while ( i != -1) ; System . out . println ( " File transferring successfully to client ");

68

Created by

Amal, Nithish, Rakesh & Vishnu

CHAPTER 12. FILE SERVER


f . close () ; ct . close () ; } } catch ( Exception er ) { System . out . println ( " Caught " + er ) ; } } public static void main ( String args []) { fileserver es = new fileserver (9999) ; es . serve () ; } } class fileclient extends Frame implements ActionListener { TextField text = null ; TextField text1 = null ; Button b = null ; client c ; public fileclient () { init () ; } void init () { addWindowListener ( new WindowAdapter () { public void windowClosing ( WindowEvent e ) { System . exit (0) ;}}) ; setLayout ( new BorderLayout () ) ; setTitle ( " Client " ) ; setSize (300 ,120) ; setVisible ( true ) ; text = new TextField (12) ; text . setText ( " Type File name to download " ) ; text . setEditable ( false ) ; add ( text , BorderLayout . NORTH ) ; text1 = new TextField (12) ; add ( text1 , BorderLayout . CENTER ) ; b = new Button ( " Send " ) ; b . addActionListener ( this ) ; add (b , BorderLayout . SOUTH ) ; } public void actionPerformed ( ActionEvent ae ) { String snd = text1 . getText () ; text1 . setText (( " " ) ) ; FileDialog f = new FileDialog ( this , " Save file as " ,1) ; f . setVisible ( true ) ; c . send ( snd , f . getDirectory () + f . getFile () ) ; text . setText ( " File saved in " + f . getDirectory () ) ; } public static void main ( String args []) { fileclient f = new fileclient () ; f . c = new client () ; } } class client { Socket cs = null ; DataInputStream dis = null ; PrintWriter pw = null ; client () { try { cs = new Socket ( " 127.0.0.1 " ,9999) ; dis = new DataInputStream ( cs . getInputStream () ) ; pw = new PrintWriter ( cs . getOutputStream () , true ) ;

Created by

69

Amal, Nithish, Rakesh & Vishnu

CHAPTER 12. FILE SERVER


} catch ( Exception e ) { } } void send ( String fileName , String newName ) { int fread ; try { pw . println ( fileName ) ; FileOutputStream f = new FileOutputStream ( newName ) ; do { fread = dis . read () ; if ( fread != -1) f . write ( fread ) ; } while ( fread != -1) ; f . close () ; } catch ( Exception e ) { System . out . println ( e ) ; } } }

70

Created by

Amal, Nithish, Rakesh & Vishnu

CHAPTER 12. FILE SERVER

Output

Figure 12.1: Output Screen

Result
The Program is executed successfully and the output is obtained.

Created by

71

Amal, Nithish, Rakesh & Vishnu

13

UDP Messaging
Description
In this chapter we describe a system which allows simple messages to be sent between two clients directly without a need for a central server. The messages are sent using User Datagram Protocol by constructing Datagram packets containing message and the receivers address. The intention of this chapter is to illustrate usage of UDP protocol. In the following sections, we have described an implementation of a simple client capable of sending message to another client and capable of receiving messages sent to it using UDP protocol.

Algorithm
Algorithm UDPSenderReciever begin Step Step Step Step Step Step Step Step Step Step load Step Step Step end 1:Start the program 2:Do Step 3 and 8 in parallel 3:Wait until a Datagram Packet arrives at the port in which the program is bound 4:Receive the Datagram Packet 5:Extract the payload to message 6:Print message 7:Goto Step 3 8:Read Receivers address and message from user 9:If message is bye Goto Step 13 10:Create datagram packet with Receivers address as address and message as Pay11:Sent this datagram Packet 12:Goto Step 8 13:Stop

73

CHAPTER 13. UDP MESSAGING

Program
import import import import java . net .*; java . awt .*; java . io .*; java . awt . event .*;

class socket extends Frame implements ActionListener { DatagramSocket s = null ; DatagramPacket p = null ; String message = " " ; InetAddress iadd = null ; int port , port1 ; Button b = null ; TextArea display = null ; TextField t = null ; public void actionPerformed ( ActionEvent ae ) { send ( t . getText () ) ; t . setText ( " " ) ; } void send ( String msg ) { byte data []= msg . getBytes () ; p = new DatagramPacket ( data , data . length , iadd , port1 ) ; try { s . send ( p ) ; message = " Sent : " + msg . trim () + " \ n " + message ; display . setText ( message ) ; } catch ( Exception e ) { } } public socket () { try { iadd = InetAddress . getByName ( " localhost " ) ; int i = port =400; port1 = port +1; do { try { s = new DatagramSocket (i , iadd ) ; if ( i != port ) { port1 =i -1; port = i ; } i =0; } catch ( Exception e ) { i ++; System . out . println ( " **** " + i ) ; } } while ( i !=0) ; setTitle ( " Port = " + port ) ; setSize (200 ,300) ; setVisible ( true ) ; display = new TextArea () ; display . setEditable ( false ) ; t = new TextField (10) ; t . setEditable ( true ) ; b = new Button ( " Send " ) ; setLayout ( new BorderLayout () ) ; add ( display , BorderLayout . NORTH ) ; add (t , BorderLayout . CENTER ) ; add (b , BorderLayout . SOUTH ) ; addWindowListener ( new WindowAdapter () { public void windowClosing ( WindowEvent e ) { System . exit (0) ;}}) ; b . addActionListener ( this ) ;

74

Created by

Amal, Nithish, Rakesh & Vishnu

CHAPTER 13. UDP MESSAGING


while ( true ) { byte datain []= new byte [50]; DatagramPacket packet = new DatagramPacket ( datain ,50) ; s . receive ( packet ) ; String str = new String ( datain ) ; message = " Received : " + str . trim () + " \ n " + message . trim () ; display . setText ( message . trim () ) ; } } catch ( Exception e ) { } } public static void main ( String a []) { socket s = new socket () ; } }

Created by

75

Amal, Nithish, Rakesh & Vishnu

CHAPTER 13. UDP MESSAGING

Output

Figure 13.1: Output Screen

Result
The Program is executed successfully and the output is obtained.

76

Created by

Amal, Nithish, Rakesh & Vishnu

14

Broadcasting
Description
Broadcasting refers to a method of transferring a message to all recipients simultaneously. In computer networking, broadcasting refers to transmitting a packet that will be received by every device on the network. In this chapter, we describe an implementation of a server which broadcasts a specic message to all the clients connected to it. The server is capable of handling multiple clients at a time. A simple implementation of the client is also described.

Algorithm
Algorithm BroadcastServer begin Step Step Step Step end Algorithm BroadcastClient begin Step Step Step Step end 1: 2: 3: 4: Connect to the server Receive message coming from server Print the message Goto Step 2 1: 2: 3: 4: Start the server Read a line from user Send this line to all connected clients Goto Step 2

Program
77

CHAPTER 14. BROADCASTING

import import import import

java . net .*; java . awt .*; java . io .*; java . awt . event .*;

class broadcast_sender extends Frame implements ActionListener { DatagramSocket s = null ; DatagramPacket p = null ; String message = " " ; InetAddress iadd = null ; int port ; Button b = null ; TextArea display = null ; TextField t = null ; public void actionPerformed ( ActionEvent ae ) { send ( t . getText () ) ; if ( t . getText () . trim () . equals ( " bye " ) ) System . exit (0) ; t . setText ( " " ) ; } void send ( String msg ) { for ( int i =400; i <9999; i ++) { try { byte data []= msg . getBytes () ; p = new DatagramPacket ( data , data . length , iadd , i ) ; s . send ( p ) ; } catch ( Exception e ) { System . out . println ( e ) ; } } message = " Sent : " + msg . trim () + " \ n " + message ; display . setText ( message ) ; } public broadcast_sender () { try { iadd = InetAddress . getByName ( " localhost " ) ; int i = port =400; do { try { s = new DatagramSocket (i , iadd ) ; port = i ; i =0; } catch ( Exception e ) { i ++; System . out . println ( " **** " + i ) ; } } while ( i !=0) ; setTitle ( " Broadcast " + port ) ; setSize (400 ,300) ; setVisible ( true ) ; display = new TextArea () ; display . setEditable ( false ) ; t = new TextField (10) ; t . setEditable ( true ) ; b = new Button ( " Send " ) ; setLayout ( new BorderLayout () ) ; add ( display , BorderLayout . NORTH ) ; add (t , BorderLayout . CENTER ) ; add (b , BorderLayout . SOUTH ) ;

78

Created by

Amal, Nithish, Rakesh & Vishnu

CHAPTER 14. BROADCASTING


addWindowListener ( new WindowAdapter () { public void windowClosing ( WindowEvent e ) { System . exit (0) ;}}) ; b . addActionListener ( this ) ; } catch ( Exception e ) { System . out . println ( e ) ; } } public static void main ( String a []) { broadcast_sender s = new broadcast_sender () ; } } class br oadcast_reciever extends Frame { DatagramSocket s = null ; DatagramPacket p = null ; String message = " " ; InetAddress iadd = null ; int port ; TextArea display = null ; public broadcast_reciever () { try { iadd = InetAddress . getByName ( " localhost " ) ; int i = port =400; do { try { s = new DatagramSocket (i , iadd ) ; port = i ; i =0; } catch ( Exception e ) { i ++; System . out . println ( " **** " + i ) ; } } while ( i !=0) ; setTitle ( " Receiver " + port ) ; setSize (300 ,300) ; setVisible ( true ) ; display = new TextArea () ; display . setEditable ( false ) ; add ( display ) ; addWindowListener ( new WindowAdapter () { public void windowClosing ( WindowEvent e ) { System . exit (0) ;}}) ; while ( true ) { byte datain []= new byte [50]; DatagramPacket packet = new DatagramPacket ( datain ,50) ; s . receive ( packet ) ; String str = new String ( datain ) ; message = " Received : " + str . trim () + " \ n " + message . trim () ; display . setText ( message . trim () ) ; } } catch ( Exception e ) { System . out . println ( e ) ; } } public static void main ( String a []) { broadcast_reciever s = new broadcast_reciever () ; } }

Created by

79

Amal, Nithish, Rakesh & Vishnu

CHAPTER 14. BROADCASTING

Output

Figure 14.1: Output Screen

Result
The Program is executed successfully and the output is obtained.

80

Created by

Amal, Nithish, Rakesh & Vishnu

15

Remote Method Invocation


Description
A remote procedure call (RPC) is an inter-process communication that allows a computer program to cause a subroutine or procedure to execute in another address space (commonly on another computer on a shared network) without the programmer explicitly coding the details for this remote interaction. That is, the programmer writes essentially the same code whether the subroutine is local to the executing program, or remote. When the software in question uses object-oriented principles, RPC is called remote invocation or remote method invocation.RMI is the Java version of a remote procedure call (RPC), but with the ability to pass one or more objects along with the request. An RPC is initiated by the client, which sends a request message to a known remote server to execute a specied procedure with supplied parameters. The remote server sends a response to the client, and the application continues its process. While the server is processing the call, the client is blocked (it waits until the server has nished processing before resuming execution). Sequence of events during a RPC 1. The client calls the client stub. The call is a local procedure call, with parameters pushed on to the stack in the normal way. 2. The client stub packs the parameters into a message and makes a system call to send the message. Packing the parameters is called marshaling. 3. The clients local operating system sends the message from the client machine to the server machine. 4. The local operating system on the server machine passes the incoming packets to the server stub. 5. The server stub unpacks the parameters from the message . Unpacking the parameters is called unmarshaling. 6. Finally, the server stub calls the server procedure. The reply traces the same steps in the reverse direction. 81

CHAPTER 15. REMOTE METHOD INVOCATION

Algorithm
Algorithm Remote Method Invocation begin // The four source les used are: //AddServerIntf.java denes remote interface that is provided by the server. //AddServerImpl.java implements the methods in remote interface. //AddServer.java contains main program for server machine. its primary function is to //update the RMI registry on that machine. //AddClient.java implements the client side of the distributed application. Step 1 :Create and Compile the source codes This will create les AddClient.class, AddServerIntf.class, AddServerImpl.class, AddServer.class Step 2 :Generate a Stub using RMI compiler. This will create le AddServerImpl Stub.class Step 3 :Install les on client and server machines Copy AddClient.class, AddServerImpl Stub.class, and AddServerIntf.class to a directory on the client machine. Copy AddServerIntf.class, AddServerImpl.class, AddServerImpl Stub.class, and AddServer.class to a directory on the server machine. Step 4 :Start RMI registry on the Server Machine Step 5 :Start the Server Step 6 :Start the Client end

Program
import import import import java . net .*; java . rmi .*; java . rmi . server .*; java . io .*;

interface AddServerInf extends Remote { public String add ( String a , String b ) throws RemoteException ; } class AddServerImp extends UnicastRemoteObject implements AddServerInf { public AddServerImp () throws RemoteException { } public String add ( String A , String B ) throws RemoteException { String c = " " ; int i , carry =0 , la , lb , lc , sum ; char a []= A . toCharArray () ; char b []= B . toCharArray () ; la = A . length () -1; lb = B . length () -1; lc =( la > lb ) ? la +1: lb ; for ( i = lc ; lb >=0&& la >=0; lb - - , la - -) { sum = a [ la ]+ b [ lb ] -48+ carry ; if ( sum -48 >9) { sum = sum -10; carry =1; } else carry =0;

82

Created by

Amal, Nithish, Rakesh & Vishnu

CHAPTER 15. REMOTE METHOD INVOCATION


c =( char ) sum + c ; } for ( i = la ; la >=0; la - -) { sum = a [ la ]+ carry ; if ( sum -48 >9) { sum = sum -10; carry =1; } else carry =0; c =( new String () ) +( char ) sum + c ; } for ( i = lb ; lb >=0; lb - -) { sum = b [ lb ]+ carry ; if ( sum -48 >9) { sum = sum -10; carry =1; } else carry =0; c =( new String () ) +( char ) sum + c ; } if ( carry ==1) { c = 1 + c ; } return c ; } } class AddServer { public static void main ( String a []) { try { AddServerImp server = new AddServerImp () ; Naming . rebind ( " AddServer1 " , server ) ; } catch ( Exception e ) { System . out . println ( " Error : " + e ) ; } } } class AddClient { public static void main ( String args []) { try { AddServerInf server =( AddServerInf ) Naming . lookup ( " rmi :// localhost / AddServer1 " ) ; String str ; String a ,b , sum ; BufferedReader br = new BufferedReader ( new InputStreamReader ( System . in ) ) ; System . out . print ( " Enter first number : " ) ; str = br . readLine () ; a =( str ) ; System . out . print ( " Enter second number : " ) ; str = br . readLine () ; b =( str ) ; sum = server . add (a , b ) ; System . out . print ( a + " + " + b + " = " + sum ) ; } catch ( Exception e ) { } } }

Created by

83

Amal, Nithish, Rakesh & Vishnu

CHAPTER 15. REMOTE METHOD INVOCATION

Output

Figure 15.1: Output Screen

Result
The Program is executed successfully and the output is obtained.

84

Created by

Amal, Nithish, Rakesh & Vishnu

16

Java Database Connectivity


Description
JDBC is a Java-based data access technology. This technology is an API for the Java programming language that denes how a client may access a database. It provides methods for querying and updating data in a database. JDBC is oriented towards relational databases. The API provides a mechanism for dynamically loading the correct Java packages and registering them with the JDBC Driver Manager. The Driver Manager is used as a connection factory for creating JDBC connections.

Algorithm
Algorithm DatabaseConnection begin //We have a database table Student with following schema Student[Sl no,Name,Mark1,Mark2,Mark3] Step 1 : Load and register JDBC driver Step 2 : Create a connection to the database Step 3 : Print MENU Step 4 : Print 1. Insert Data Step 5 : Print 2. Update Data Step 6 : Print 3. Display Class Details Step 7 : Print 4. Exit Step 8 : Print Enter Your Choice Step 9 : Read choice from user Step 10 : if choice is 4 goto step 25 Step 11 : if choice is 3 goto step 21 Step 12 : if choice is 2 goto step 17 Step 13 : Read name, mark1, mark2,mark3 from user Step 14 : Create a query for insertion with these details Step 15 : Execute query Step 16 : goto step 3 Step 17 : Read name, new mark1, new mark2,new mark3 from user Step 18 : Create a query for update marks of name with new mark1,new mark2,new mark3 85

CHAPTER 16. JAVA DATABASE CONNECTIVITY Step Step Step Step Step Step Step end 19 20 21 22 23 24 25 : : : : : : : Execute query goto step 3 Create a query for select the class details Execute query and store the data in result Display the result goto step 3 Stop

Program
/* SQL create database jdbc ; use jdbc ; create table student ( r_no int primary key , name varchar (20) ) ; */ import java . sql .*; import java . io .*; // java - cp mysql - connector - java -5.0.8 - bin . jar ; jdbc class jdbc { Connection connect = null ; Statement statement = null ; public static void main ( String args []) { int choice ; String line , name ; int r_no ; BufferedReader br = new BufferedReader ( new InputStreamReader ( System . in ) ) ; jdbc J = new jdbc () ; do { choice = J . menu () ; switch ( choice ) { case 0: System . exit (0) ;; case 1: try { System . out . print ( " Enter roll no : " ) ; line = br . readLine () ; r_no = Integer . parseInt ( line ) ; System . out . print ( " Enter Name : " ) ; name = br . readLine () ; J . insert ( r_no , name ) ; } catch ( Exception e ) { System . out . println ( e ) ; } break ; case 2: try { System . out . print ( " Enter roll no : " ) ; line = br . readLine () ; r_no = Integer . parseInt ( line ) ; J . delete ( r_no ) ; } catch ( Exception e ) { System . out . println ( e ) ; } break ; case 3: J . view () ; break ; } } while ( true ) ; }

86

Created by

Amal, Nithish, Rakesh & Vishnu

CHAPTER 16. JAVA DATABASE CONNECTIVITY


public jdbc () { try { Class . forName ( " com . mysql . jdbc . Driver " ) ; connect = DriverManager . getConnection ( " jdbc : mysql :// localhost / student ? user = root " ) ; statement = connect . createStatement () ; } catch ( Exception e ) { System . out . println ( e ) ; } } int menu () { try { String s ; System . out . print ( " \ n1 . Insert \ t2 . Delete \ n3 . View \ t \ t0 . Exit \ nEnter your choice (0 -3) : " ) ; BufferedReader br = new BufferedReader ( new InputStreamReader ( System . in ) ) ; s = br . readLine () ; return Integer . parseInt ( s ) ; } catch ( Exception e ) { return menu () ; } } void insert ( int r_no , String name ) { try { statement . executeUpdate ( " insert into student values ( " + r_no + " ," + name + " ) " ) ; } catch ( Exception e ) { System . out . println ( e ) ;} } void delete ( int r_no ) { try { statement . executeUpdate ( " delete from student where r_no = " + r_no + " " ) ; } catch ( Exception e ) { System . out . println ( e ) ;} } void view () { try { ResultSet resultset = statement . executeQuery ( " select * from student " ) ; while ( resultset . next () ) System . out . println ( " Roll number : " + resultset . getString ( " r_no " ) + " \ tName : " + resultset . getString ( " name " ) ) ; } catch ( Exception e ) { System . out . println ( e ) ; } } }

Created by

87

Amal, Nithish, Rakesh & Vishnu

CHAPTER 16. JAVA DATABASE CONNECTIVITY

Output

Figure 16.1: Output Screen

Result
The Program is executed successfully and the output is obtained.

88

Created by

Amal, Nithish, Rakesh & Vishnu

17

Extended Markup Language


Description
XML les are used to transport structured data across network. In this chapter we have constructed an XML le containing syllabus of a subject and created a corresponding XML Stylesheet Language le which describes formatting of elements for the XML document. Finally the XML le is displayed in a web browser.

Program
Syllabus.xml
<? xml version = " 1.0 " ? > <! DOCTYPE syllabus [ <! ELEMENT syllabus ( subject , code , module +) > <! ELEMENT subject (# PCDATA ) > <! ELEMENT code (# PCDATA ) > <! ELEMENT module ( srno , name , topic +) > <! ELEMENT srno (# PCDATA ) > <! ELEMENT name (# PCDATA ) > <! ELEMENT topic (# PCDATA ) > ]> <? xml - stylesheet type = " text / xsl " href = " SyllabusStyle . xsl " ? > < syllabus > < subject > OPTIMIZATION TECHNIQUES ( ELECTIVE - I ) </ subject > < code > CMELRTA 706 -1 </ code > < module > < srno >1 </ srno > < name > Classical optimization techniques </ name > < topic > Single variable optimization </ topic > < topic > Multivariable optimization with no constraints </ topic > < topic > Hessian matrix </ topic > < topic > Multivariable saddle point </ topic > < topic > Optimization with equality constraints </ topic > < topic > Kuhn - Tucker conditions </ topic > </ module > < module > < srno >2 </ srno > < name > One dimensional unconstrained minimization </ name > < topic > Elimination metods </ topic >

89

CHAPTER 17. EXTENDED MARKUP LANGUAGE


< topic > unrestricted search method </ topic > < topic > Fibonacci method </ topic > < topic > Interpolation methods </ topic > < topic > Quadratic interpolation and </ topic > < topic > cubic interpolation metods . </ topic > </ module > < module > < srno >3 </ srno > < name > Unsonstrained minimization </ name > < topic > Gradient of function </ topic > < topic > Steepest descent method </ topic > < topic > Newtons method </ topic > < topic > Powells method </ topic > < topic > Hooke and Jeeves method </ topic > < topic > Summary </ topic > </ module > </ syllabus >

SyllabusStyle.xsl
<? xml version = " 1.0 " encoding = " ISO -8859 -1 " ? > < xsl : stylesheet version = " 1.0 " xmlns : xsl = " http :// www . w3 . org /1999/ XSL / Transform " > < xsl : template match = " / " > < html > < body style = " background - color : white " > < div style = " width : 500 px ; height : 540 px ; margin : auto ; border :3 px solid rgb (209 , 209 , 209) ; " > < div style = " width :500 px ; height :50 px ; background - color : rgb (209 , 209 , 209) ; text - align : center ; " > < span style = " font - size :20 px ; line - height :50 px " > < xsl : value - of select = " syllabus / subject " / > </ span > </ div > < div style = " width :500 px ; height :30 px ; background - color : white ; " > < span style = " font - size :20 px ; line - height :30 px " > Subject Code : < xsl : value - of select = " syllabus / code " / > </ span > </ div > < xsl : for - each select = " syllabus / module " > < div style = " width : 500 px ; height : 150 px ; " > < div style = " width :500 px ; height :20 px ; background - color : rgb (209 , 209 , 209) ; " > < span style = " font - size :18 px ; line - height :20 px " > Module Name : < xsl : value - of select = " name " / > </ span > </ div > < xsl : for - each select = " topic " > < div style = " width :500 px ; height :20 px ; " > < span style = " font - size :18 px ; line - height :20 px " > < xsl : value - of select = " . " / > </ span > </ div > </ xsl : for - each > </ div > </ xsl : for - each > </ div > </ body > </ html > </ xsl : template > </ xsl : stylesheet >

90

Created by

Amal, Nithish, Rakesh & Vishnu

CHAPTER 17. EXTENDED MARKUP LANGUAGE

Output

Figure 17.1: Output Screen

Result
The Program is executed successfully and the output is obtained.

Created by

91

Amal, Nithish, Rakesh & Vishnu

18

Java Server Pages


Description
JSP is a java based server technology that can create dynamic web pages. It allows embedding java code within static webpage content and hence bring the power of java language into server side processing. In the following section of this chapter we describe a creation of a JSP page that when requested can return a webpage(html page) that shows a library management system.

Program
library.jsp
<! - A JSP file to display the details of a book entered through the above shown form . --> < html > < title > Libray Management System </ title > < body > < font color = " brown " face = " times new roman " size = " 6 " ><b > < center > Library Book Catalog </ center > </b > </ font > < br / > < table bgcolor = " lightgray " align = " center " width = " 500 " height = " 300 " > <tr > <td > <b > Accession No </ b > </ td > <td >: </ td > <td > <b > <%= request . getParameter ( " accno " ) % > </b > </ td > </ tr > <tr > <td > <b > Title </ b > </ td > <td >: </ td > <td > <b > <%= request . getParameter ( " title " ) % > </b > </ td > </ tr > <tr > <td > <b > Publisher </ b > </ td > <td >: </ td > <td > <b > <%= request . getParameter ( " publ " ) % > </b > </ td >

93

CHAPTER 18. JAVA SERVER PAGES


</ tr > <tr > <td > <b > Author </ b > </ td > <td >: </ td > <td > <b > <%= request . getParameter ( " author " ) % > </b > </ td > </ tr > <tr > <td > <b > Publishing Date </ b > </ td > <td >: </ td > <td > <b > <%= request . getParameter ( " pubdate " ) % > </b > </ td > </ tr > <tr > <td > <b > Purchasing Date </ b > </ td > <td >: </ td > <td > <b > <%= request . getParameter ( " purdate " ) % > </b > </ td > </ tr > <tr > <td > <b > Status </ b > </ th > <td >: </ td > <td > <b > <%= request . getParameter ( " status " ) % > </b > </ td > </ tr > </ table > </ body > </ html >

library.html
<! - HTML code to display a form . The form helps to enter the details of a book --> < html > < title > Library Management System </ title > < body > < center > < font color = " brown " face = " times new roman " size = " 7 " > Library Book Log </ font > < br / > < br / > < font face = " times new roman " size = " 4 " ><b > Fill the following fields with the relevant information . </b > </ font > < form method = " post " action = " library . jsp " >< br / > < table border = " 0 " align = " center " width = " 405 " bgcolor = " lightgray " > <tr > <td > <b > Accession No </b > </ td > < td >: </ td > <td > < input name = " accno " size = " 40 " > </ td > </ tr > <tr > <td > <b > Title </b > </ td > < td >: </ td > <td > < input name = " title " size = " 40 " > </ td > </ tr > <tr > <td > <b > Publisher

94

Created by

Amal, Nithish, Rakesh & Vishnu

CHAPTER 18. JAVA SERVER PAGES


</b > </ td > < td >: </ td > <td > < input name = " publ " size = " 40 " > </ td > </ tr > <tr > <td > <b > Author </b > </ td > < td >: </ td > <td > < input name = " author " size = " 40 " > </ td > </ tr > <tr > <td > <b > Publishing Date </b > </ td > < td >: </ td > <td > < input name = " pubdate " size = " 40 " > </ td > </ tr > <tr > <td > <b > Purchasing Date </b > </ td > < td >: </ td > <td > < input name = " purdate " size = " 40 " > </ td > </ tr > <tr > <td > <b > Status </b > </ td > < td >: </ td > <td > < select name = " status " > < option value = " issued " > Issued </ option > < option value = " present in the library " > Present in the Library </ option > < option value = " reference " > Reference </ option > < option value = " cannot be issued " > Cannot be Issued </ option > </ select > </ td > </ tr > <tr > <td > </ td > <td > </ td > < td align = " right " > < input type = " submit " value = " submit " id = " submit " name = " submit " > </ td > </ tr > </ table > </ form > </ center > </ body >

Created by

95

Amal, Nithish, Rakesh & Vishnu

CHAPTER 18. JAVA SERVER PAGES

Output

Figure 18.1: Output Screen

96

Created by

Amal, Nithish, Rakesh & Vishnu

CHAPTER 18. JAVA SERVER PAGES

Output

Figure 18.2: Output Screen

Result
The Program is executed successfully and the output is obtained.

Created by

97

Amal, Nithish, Rakesh & Vishnu

19

Java Applet
Description
A Java applet is an applet delivered to users in the form of Java bytecode. Java applets can run in a Web browser using a Java Virtual Machine (JVM), or in Suns AppletViewer, a stand-alone tool for testing applets. Java applets run at very fast speeds than JavaScript. In addition they can use 3D hardware acceleration that is available from Java. This makes applets well suited for non-trivial, computation intensive visualizations to web based applications entirely computed in the client side. In this Chapter we describe creation of an applet which can draw a circle and then daw a continuously revolving tangent to the circle. This result can be displayed in a web browser easily.

Algorithm
Algorithm TangentToCircle(r,xc ,yc ,L) begin //r is the radius of the circle to be drawn with center at point (xc ,yc ) //The length of the tangent is L //The end points of tangent is derived from the fact that the locus of end points of the //tangent revolving around the circle forms a bigger circle with radius L2 + r2 and the //angular separation between the 2 points is tan1 ( L ) r //drawCircle(r,xc ,yc ) draws a circle centered at (xc ,yc ) with radius r //drawLine(x1 ,y1 ,x2 ,y2 ) draws a line from (x1 ,y1 ) to (x2 ,y2 ) Step 1: Start the program Step 2: Set :=0 Step 3: :=+1 Step 4: x1 := L2 + r2 cos() Step 5: y1 := L2 + r2 sin() Step 6: x2 := L2 + r2 cos( + tan1 ( L )) r Step 7: y2 := L2 + r2 sin( + tan1 ( L )) r Step 8: drawCircle(r,xc ,yc ) Step 9: drawLine(x1 ,y1 ,x2 ,y2 ) 99

CHAPTER 19. JAVA APPLET Step 10: Goto Step 3 Step 11: Stop end

Program
/* < applet code = MyApplet . class width =350 height =350 > </ applet > <! - */ import java . applet .*; import java . awt .*; public class MyApplet extends Applet { public void paint ( Graphics g ) { double i , x1 , y1 , x2 , y2 ; int r =100 , xc =150 , yc =150 , color =0; for ( i =0; true ; i +=(3.14/180) ) { x1 =( int ) ( r * Math . sqrt (2) * Math . cos ( i ) ) + xc ; y1 =( int ) ( r * Math . sqrt (2) * Math . sin ( i ) ) + yc ; x2 =( int ) ( r * Math . sqrt (2) * Math . cos ( i +3.14/2) ) + xc ; y2 =( int ) ( r * Math . sqrt (2) * Math . sin ( i +3.14/2) ) + yc ; g . setColor ( Color . red ) ; g . drawOval ( xc -r , yc -r ,2* r ,2* r ) ; g . drawLine (( int ) x1 ,( int ) y1 ,( int ) x2 ,( int ) y2 ) ; try { Thread . sleep (8) ; } catch ( Exception e ) { } g . setColor ( Color . white ) ; g . drawLine (( int ) x1 ,( int ) y1 ,( int ) x2 ,( int ) y2 ) ; } } } // - - >;

100

Created by

Amal, Nithish, Rakesh & Vishnu

CHAPTER 19. JAVA APPLET

Output

Figure 19.1: Output Screen

Result
The Program is executed successfully and the output is obtained.

Created by

101

Amal, Nithish, Rakesh & Vishnu

20

HTTP Server
Description
In this Experiment we tried to create a simple HTTP server program in java. This java program starts running and binds itself to a predened port. From this state onwards it listens to the port for http connection requests from client. After accepting connection requests it responds to the request but responding with the resource client has requested. The server only acknowledges request for plain html les or plain text les.

Program
HTTPServer.java
/* Directory Structure * HOME DIRECTORY | - - - HTTPServer . java | - - - HTTPServer . class | - - - Home . html | - - - page1 . html | - - - page2 . html | - - - error . html */ import java . io .*; import java . net .*; import java . util .*; class HTTPServer extends Thread { Socket connectedClient = null ; BufferedReader inFromClient = null ; DataOutputStream outToClient = null ; public HTTPServer ( Socket client ) { connectedClient = client ; } public void run () {

103

CHAPTER 20. HTTP SERVER


try { System . out . println ( " \ n \ nNEW REQUEST \ n \ n " ) ; System . out . println ( " The Client " + connectedClient . getInetAddress () + " : " + connectedClient . getPort () + " is connected " ) ; inFromClient = new BufferedReader ( new InputStreamReader ( connectedClient . getInputStream () ) ) ; outToClient = new DataOutputStream ( connectedClient . getOutputStream () ) ; String requestString = inFromClient . readLine () ; String headerLine = requestString ; StringTokenizer tokenizer = new StringTokenizer ( headerLine ) ; String httpMethod = tokenizer . nextToken () ; String httpQueryString = tokenizer . nextToken () ; StringBuffer responseBuffer = new StringBuffer () ; System . out . println ( " Parameters of the HTTP Request " ) ; while ( inFromClient . ready () ) { // Reading the HTTP complete HTTP Query responseBuffer . append ( requestString + " <BR > " ) ; System . out . println ( requestString ) ; requestString = inFromClient . readLine () ; } if ( httpMethod . equals ( " GET " ) ) { if ( httpQueryString . equals ( " / " ) ) { // no resource is requested String header = " <b > Parameters of the HTTP Request </ b > </ br > " ; sendResponse (200 , header + responseBuffer . toString () , false ) ; } else { // This is interpreted as a file name String fileName = httpQueryString . replaceFirst ( " / " , " "); if ( new File ( fileName ) . isFile () ) { sendResponse (200 , fileName , true ) ; } else { sendResponse (404 , " error . html " , true ) ; } } } else sendResponse (404 , " error . html " , true ) ; } catch ( Exception e ) { e . printStackTrace () ; } } public void sendResponse ( int statusCode , String responseString , boolean isFile ) throws Exception { final String HTML_START = " < html > < title > HTTP Server in java </ title > < body > " ; final String HTML_END = " </ body > </ html > " ; String statusLine = null ; String serverdetails = " Server : Java HTTPServer " ;

104

Created by

Amal, Nithish, Rakesh & Vishnu

CHAPTER 20. HTTP SERVER


String contentLengthLine = null ; String fileName = null ; String contentTypeLine = " Content - Type : text / html " + " \ r \ n " ; FileInputStream fin = null ; if ( statusCode == 200) statusLine = " HTTP /1.1 200 OK " + " \ r \ n " ; else statusLine = " HTTP /1.1 404 Not Found " + " \ r \ n " ; if ( isFile ) { fileName = responseString ; fin = new FileInputStream ( fileName ) ; contentLengthLine = " Content - Length : " + Integer . toString ( fin . available () ) + " \ r \ n " ; if (! fileName . endsWith ( " . htm " ) && ! fileName . endsWith ( " . html " ) ) contentTypeLine = " Content - Type : \ r \ n " ; } else { responseString = HTML_START + responseString + HTML_END ; contentLengthLine = " Content - Length : " + responseString . length () + " \ r \ n " ; } outToClient . writeBytes ( statusLine ) ; outToClient . writeBytes ( serverdetails ) ; outToClient . writeBytes ( contentTypeLine ) ; outToClient . writeBytes ( contentLengthLine ) ; outToClient . writeBytes ( " Connection : close \ r \ n " ) ; outToClient . writeBytes ( " \ r \ n " ) ; if ( isFile ) sendFile ( fin , outToClient ) ; else outToClient . writeBytes ( responseString ) ; outToClient . close () ; } public void sendFile ( FileInputStream fin , DataOutputStream out ) { // throws Exception { byte [] buffer = new byte [1024] ; int bytesRead ; try { while (( bytesRead = fin . read ( buffer ) ) != -1 ) { out . write ( buffer , 0 , bytesRead ) ; } fin . close () ; } catch ( Exception e ) { try { out . writeBytes ( " File Read ERROR " ) ; } catch ( IOException e1 ) { e1 . printStackTrace () ; } } } public static void main ( String args []) throws Exception { ServerSocket Server = new ServerSocket (6789 , 10 , InetAddress . getByName ( " 6.6.6.6 " ) ) ; System . out . println ( " HTTP SERVER Running on port 6789 " ) ; while ( true ) { Socket connected = Server . accept () ; ( new HTTPServer ( connected ) ) . start () ; }

Created by

105

Amal, Nithish, Rakesh & Vishnu

CHAPTER 20. HTTP SERVER


} }

Home.html
< html > < head > </ head > < body > < h1 style = " color : red ; " > <b > This is the home page </ b > </ h1 > <br > < span > Click <a href = " page1 . html " > here </ a > to view page1 . html and <a href = " page2 . html " > here </ a > to view page2 . html </ span > </ body > </ html >

Page1.html
< html > < head > </ head > < body > < h1 style = " color : red ; " > <b > This is page1 </ b > </ h1 > <br > < span > Click <a href = " home . html " > here </ a > to view homepage and <a href = " page2 . html " > here </ a > to view page2 . html </ span > </ body > </ html >

Page2.html
< html > < head > </ head > < body > < h1 style = " color : red ; " > <b > This is page2 </ b > </ h1 > <br > < span > Click <a href = " home . html " > here </ a > to view homepage and <a href = " page1 . html " > here </ a > to view page1 . html </ span > </ body > </ html >

Error.html
< html > < head > </ head > < body > < h1 style = " color : red ; " > <b > The Requested resource not found !! </ b > </ h1 >

106

Created by

Amal, Nithish, Rakesh & Vishnu

CHAPTER 20. HTTP SERVER


< span > Click <a href = " home . html " > here </ a > to view homepage </ span > <br > < span > Usage : http : // [ Address ]:[ Port number ]/[ Resource address ] </ span > </ body > </ html >

Created by

107

Amal, Nithish, Rakesh & Vishnu

CHAPTER 20. HTTP SERVER

Output

Figure 20.1: Output Screen

108

Created by

Amal, Nithish, Rakesh & Vishnu

CHAPTER 20. HTTP SERVER

Output

Figure 20.2: Output Screen

Created by

109

Amal, Nithish, Rakesh & Vishnu

CHAPTER 20. HTTP SERVER

Output

Figure 20.3: Output Screen

110

Created by

Amal, Nithish, Rakesh & Vishnu

CHAPTER 20. HTTP SERVER

Output

Figure 20.4: Output Screen

Created by

111

Amal, Nithish, Rakesh & Vishnu

CHAPTER 20. HTTP SERVER

Output

Figure 20.5: Output Screen

Result
The Program is executed successfully and the output is obtained.

112

Created by

Amal, Nithish, Rakesh & Vishnu

21

HTTP Client
Description
In this Experiment we tried to create a simple HTTP client program in java. This java program has the capability to send HTTP page requests for a URL. The program prints the result it receives back from the server.

Program
import java . net .*; import java . io .*; import java . util . Date ; class HTTPClient { public static void main ( String args []) throws Exception { int c ; URL hp = new URL ( " http :// www . rtcgeci . host22 . com / team . php " ) ; URLConnection hpCon = hp . openConnection () ; int len = hpCon . getContentLength () ; if ( len == -1) System . out . println ( " Content length unavailable . " ) ; else System . out . println ( " Content - Length : " + len ) ; if ( len != 0) { InputStream input = hpCon . getInputStream () ; int i = len ; while ((( c = input . read () ) != -1) ) { if ( c == \ t ) { System . out . print ( " \ n " ) ; } System . out . print (( char ) c ) ; } input . close () ; } else { System . out . println ( " No content available . " ) ; } } }

113

CHAPTER 21. HTTP CLIENT

Output

Figure 21.1: Output Screen

Result
The Program is executed successfully and the output is obtained.

114

Created by

Amal, Nithish, Rakesh & Vishnu

22

Implementation of Ping Command


Description
The ping command is a Command Prompt command available in linux and windows and many other operating system. This command is used to test the ability of the source computer to reach a specied destination computer. The ping command is usually used as a simple way verify that a computer can communicate over the network with another computer or network device. Ping command works by sending echo requests to destination computer and seeing if destination computer responds back or not. The Standard ping command supplies much more information like round trip time. In this experiment we have tried to implement an limited ping command which can test wether a destination computer can be reached or not.

Algorithm
Algorithm Ping begin Step Step Step Step Step Step Step end 1:Start the program 2:Start timer 3:Send an echo request to source computer 4:Wait till source computer responds 5:Stop the timer when Echo request is acknowledged 6:Print the value of timer 7:Stop

Program
import java . net .*; import java . io .*; import java . util . regex .*; public class Ping {

115

CHAPTER 22. IMPLEMENTATION OF PING COMMAND


public static void main ( String args []) { long connectStart =0 , connectFinish = 0; String host ; int responseCode =0; if ( args . length <1) { System . out . println ( " Usage :\ tPing host " ) ; return ; } else if ( Pattern . matches ( " .*([://]) .* " , args [0]) ) host = args [0]; else host = " http :// " + args [0]; try { HttpURLConnection connection = ( HttpURLConnection ) new URL ( host ) . openConnection () ; connection . setRequestMethod ( " HEAD " ) ; connectStart = System . currentTimeMillis () ; responseCode = connection . getResponseCode () ; connectFinish = System . currentTimeMillis () ; if ( responseCode < 100) { System . out . println ( " undetermined . " ) ; } else if ( responseCode < 200) { System . out . println ( " informal ( shouldn t happen on a GET / HEAD ) " ) ; } else if ( responseCode < 300) { System . out . println ( " \ n \ tSuccess \ n \ tTime Delay : " +( connectStart + connectFinish ) ) ; } else if ( responseCode < 400) { System . out . println ( " \ n \ tRedirect \ n \ tTime Delay : " +( connectStart + connectFinish ) ) ; } else if ( responseCode <500 ) { System . out . println ( " Client error " ) ; } else if ( responseCode < 600) { System . out . println ( " Server Error " ) ; } } catch ( Exception e ) { System . out . println ( " Can not connect " ) ; } } }

116

Created by

Amal, Nithish, Rakesh & Vishnu

CHAPTER 22. IMPLEMENTATION OF PING COMMAND

Output

Figure 22.1: Output Screen

Result
The Program is executed successfully and the output is obtained.

Created by

117

Amal, Nithish, Rakesh & Vishnu

Part IV

References

119

23

Book References
1. Java: The Complete Reference (7th Edition) by Herbert Schildt from Tata McGraw-Hill 2. Java Database Programming Bible by Jhon ODonahue from Jhon Wiley and Sons 3. Computer Networks (5th Edition) by Andrew S. Tanenbaum and David J. Wetherall 4. JSP: The Complete Reference by Phil Hanna from Tata McGraw-Hill 5. Core Servlets and Java Server Pages by Marty Hall. 6. Web Development with Java Server Pages by Fields and Kolb. 7. Professional JSP by Karl Avedal et al. 8. JavaServer Pages (3th Edition) by Hans Bergsten 9. Beginning Java Server Pages by Vivek Chopra, Jon Eaves, Rupert Jones and Sing Li 10. XML: The Complete Reference by Heather Williamson from Tata McGraw-Hill

121

24

Web References
1. http://docs.oracle.com http://docs.oracle.com/javase/6/docs/api/java/sql/DriverManager.html http://docs.oracle.com/javase/6/docs/api/java/sql/package-summary.html http://docs.oracle.com/javase/6/docs/api/java/sql/Connection.html http://docs.oracle.com/javase/6/docs/api/java/sql/ResultSet.html http://docs.oracle.com/javase/6/docs/api/java/sql/Statement.html http://www.oracle.com/technetwork/java/javaee/jsp/index.html 2. http://docstore.mik.ua/orelly/java-ent/jnut/ch16 01.htm#javanut3-java.net-1 3. http://google.com 4. http://javaworld.com/javaworld/jw-12-1996/jw-12-sockets.html 5. www.jsums.edu 6. http://w3.org/XML/ 7. http://wikibooks.org/ http://en.wikibooks.org/wiki/Java Programming/JSP 8. http://wikipedia.org http://en.wikipedia.org/wiki/Communications protocol http://en.wikipedia.org/wiki/Transmission Control Protocol http://en.wikipedia.org/wiki/SMTP http://en.wikipedia.org/wiki/Asynchronous Transfer Mode http://en.wikipedia.org/wiki/Connectionless protocol http://en.wikipedia.org/wiki/Hypertext Transfer Protocol 123

CHAPTER 24. WEB REFERENCES http://en.wikipedia.org/wiki/Internet Protocol http://en.wikipedia.org/wiki/User Datagram Protocol http://en.wikipedia.org/wiki/Peer-to-peer http://en.wikipedia.org/wiki/Java Database Connectivity http://en.wikipedia.org/wiki/Broadcasting (networking) http://en.wikipedia.org/wiki/Online chat http://en.wikipedia.org/wiki/Echo Protocol http://en.wikipedia.org/wiki/File server http://en.wikipedia.org/wiki/Uploading and downloading http://en.wikipedia.org/wiki/XML http://en.wikipedia.org/wiki/Java Servlet http://en.wikipedia.org/wiki/JavaServer Pages http://en.wikipedia.org/wiki/User Datagram Protocol http://en.wikipedia.org/wiki/Java applet http://en.wikipedia.org/wiki/XML

124

Created by

Amal, Nithish, Rakesh & Vishnu