Upload
rakesh-k-r
View
141
Download
0
Tags:
Embed Size (px)
DESCRIPTION
Network Lab Record
Citation preview
NETWORK PROGRAMMINGLABORATARY MANUAL
Amal P.MNithish DivakarRakesh K.R
Vishnu M Santosh
Departement Of Computer Science And EngineeringGovernment Engineering College, Idukki
Preface
The book named ”Network Programming Laboratory Manual is designed in connection withthe network programming lab in the Seventh Semester Computer Science and Engineering. At-tempts have been made to present network concepts, Berkeley sockets, network programming injava, Java Database Connectivity(JDBC), Remote method invocation(RMI), Extensile Markuplanguage(XML), Java Server pages(JSP) etc.
In addition, examples in areas of Connection oriented communication, connection less com-munication, JDBC, Remote Method Invocation, XML and Java Server Pages have been workedout 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 networkmodels 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 profit. On the course of producingthis material, we have referred many websites as well as several text books each of them have beenacknowledged 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 readeris advised to check other valid sources before assuming the correctness of materials provided herewith.
Acknowledgement
This work is the output of the sincere efforts we have made for one semester. We express theAlmighty for the blessings incurred on us for the preparation of this work. The book is fullydeveloped in the Laboratories of Govt. Engineering College, Idukki. We express our sinceregratitude to the faculty and other staff of Govt. engineering College, Idukki for their help andcoordination. We also express our sincere thanks to all including our parents and friends whohave helped us directly or indirectly in the preparation of this manual.
Finally we also thank Donal E Knuth and Leslie Lamport for creating TEX and LATEX aswithout these softwares, our work would have never seen completion.
Amal P MNithish DivakarRakesh K RVishnu M SantoshStudents of Computer Science and Engineering2009-2013 batchGovt. Engineering College, Idukki
Contents
Basic Concepts of Networking 9
1 Basic Concepts of Networking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111.1 Addressing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111.2 Protocols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111.3 Network Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
2 Networking Hardwares . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152.1 Gateway . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152.2 Router . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152.3 Bridge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162.4 Switch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162.5 Hubs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162.6 Repeaters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Networking Technologies 19
3 Berkeley Socket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213.1 Berkeley Socket API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213.2 Header Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213.3 Methods of Berkeley Socket API . . . . . . . . . . . . . . . . . . . . . . . . . . . 213.4 Modes of Berkeley Sockets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
4 Networking in java . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254.1 Network Programming and Java . . . . . . . . . . . . . . . . . . . . . . . . . . . 254.2 Java.net Package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254.3 Java.rmi Package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284.4 Java.sql Package . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
5 Java Server Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315.1 Introduction to JSP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315.2 Advantages of JSP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315.3 How JSP Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325.4 Components of a JSP page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
6 Extended Markup Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
7
CONTENTS
6.1 What is XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356.2 Structure of XML Document. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356.3 Components of an XML Document . . . . . . . . . . . . . . . . . . . . . . . . . . 356.4 Syntax rules of XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376.5 Advantages of using XML . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
7 Applets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397.1 Java Applet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397.2 Capabilities of an Applet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397.3 Advantages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407.4 Applet Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407.5 The HTML APPLET Tag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Experiments 43
8 Connecting Two Computers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
9 Berkeley Socket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49
10 Echo Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
11 Chatting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
12 File Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
13 UDP Messaging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
14 Broadcasting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
15 Remote Method Invocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
16 Java Database Connectivity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
17 Extended Markup Language . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
18 Java Server Pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
19 Java Applet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 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
9
1
Basic Concepts of Networking
A computer network, or simply a network, is a collection of computers interconnected by commu-nication channels that allow sharing of resources and information. Hence a network is a frame-work in which the connected machines can exchange information. This requirement raises issueslike how each machine is individually identified, how the data is exchanged between machine,how the communication is actually conducted etc. Addressing these issues, several networkingstandards related to addressing schemes, communication protocols, connection paradigms etc.have been developed. Also, based on how a machine acts during its communication gave rise todevelopment of two distinct network models; client server model and peer to peer model.
1.1 Addressing
Every machine connected to the network is uniquely identified by a 4-byte address called InternetProtocol address . This is typically written in dotted quad format like 128.250.25.158 where eachbyte is an unsigned value between 0 and 255. But a machine in network may be required toprovide many services at same time. To distinguish these services, a concept of ports, a logicalaccess point, represented by a 16-bit integer number is used. That means, each service offeredby a machine is uniquely identified by a port number.
1.2 Protocols
Communications protocols defines the syntax, semantics for exchanging information in a com-puter network. Communication Protocols addresses many issues like Data formats and AddressFormats for Data exchange, Address mapping and Detection of transmission errors. Protocolsmay include signaling, authentication and error detection and correction capabilities. As far asnetworking is concerned, all communication protocol can be broadly classified into connection-oriented and connectionless protocol
Connection-oriented Protocols
A connection-oriented protocol is a protocol which established a connection to the receiver andthen 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 canbe made to deliver data in same order as they were sent and they can also guarantee error freetransmission by implementing error detection and correction schemes. Because they first setupa connection to the host initially, they are substantially slower than there connectionless counterparts. But they are useful in uninterrupted and secure transmissions. Some of connection-oriented protocols are:
• Transmission Control Protocol(TCP)TCP provides reliable, ordered delivery of a stream of octets from a program on onecomputer to another program on another computer. TCP is the protocol used by majorInternet applications such as the World Wide Web, email, remote administration and filetransfer.
• Simple Mail Transfer Protocol (SMTP)SMTP is an Internet standard for electronic mail (e-mail) transmission across InternetProtocol (IP) networks.
• Asynchronous Transfer Mode (ATM)ATM uses asynchronous time-division multiplexing, and it encodes data into small, fixed-sized cells. ATM uses a connection-oriented model in which a virtual circuit must beestablished between two endpoints before the actual data exchange begins. ATM is a coreprotocol 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 mes-sage can be sent from one end point to another without prior arrangement. The device at oneend of the communication transmits data addressed to the other, without first ensuring that therecipient is available and ready to receive the data. Some protocols allow for error correction byrequested retransmission. Some connectionless protocols are:
• Hypertext Transfer Protocol (HTTP)HTTP is an application protocol for distributed, collaborative, hypermedia informationsystems. HTTP is the foundation of data communication for the World Wide Web. HTTPis the protocol to exchange or transfer hypertext. HTTP functions as a request-responseprotocol in the client-server computing model. A web browser, for example, may be theclient 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 providesresources such as HTML files and other content, or performs other functions on behalfof the client, returns a response message to the client. The response contains completionstatus information about the request and may also contain requested content in its messagebody.
• User Datagram Protocol (UDP)UDDP is one of the core members of the Internet protocol suite, the set of network protocolsused for the Internet. With UDP, computer applications can send messages, in this casereferred to as datagrams, to other hosts on an Internet Protocol (IP) network without priorcommunications 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 Suiteresponsible for routing packets across network boundaries. It is the primary protocol thatestablishes the Internet.
1.3 Network Models
Based on how communication between two machines in a network is achieved, the mode of com-munication can be classified as connection oriented and connection-less. In connection orientedmode, two machines must establish an implicit connection between them to communicate whereas 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 server’s 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 thenetwork can act as a client or server for the other computers in the network, allowing sharedaccess to various resources such as files, peripherals, and sensors without the need for a centralserver. P2P is a distributed application architecture that partitions tasks or workloads amongpeers. Peers are equally privileged participants in the application. Each computer in the networkis referred to as a node. The owner of each computer on a P2P network would set aside a portionof its resources - such as processing power, disk storage, or network bandwidth - to be madedirectly available to other network participant, without the need for central coordination byservers or stable hosts.
Created by
Amal, Nithish, Rakesh & Vishnu
13
2
Networking Hardwares
Networking hardware or networking equipment typically refers to devices facilitating the use ofa computer network. Typically, this includes gateways, routers, network bridges, switches, hubs,and repeaters. Computer networking devices are also called network equipment, IntermediateSystems (IS) or InterWorking Unit (IWU). Units which are the last receiver or generate data arecalled hosts or data terminal equipment. The most common kind of networking hardware todayis copper-based Ethernet adapters, helped largely by its standard inclusion on most moderncomputer systems.
2.1 Gateway
A gateway is a network point that acts as an entrance to another network. A gateway maycontain devices such as protocol translators, impedance matching devices, rate converters, faultisolators, or signal translators as necessary to provide system interoperability. It also requiresthe establishment of mutually acceptable administrative procedures between both networks. Aprotocol translation/mapping gateway interconnects networks with different network protocoltechnologies by performing the required protocol conversions. While forwarding an IP packet toanother 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 overlayinternetwork. A router is connected to two or more data lines from different networks. When adata packet comes in one of the lines, the router reads the address information in the packet todetermine 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 ”traffic directing”functions on the Internet. When multiple routers are used in interconnected networks, the routersexchange information about destination addresses, using a dynamic routing protocol. Each routerbuilds up a table listing the preferred routes between any two systems on the interconnectednetworks. A router has interfaces for different physical types of network connections, (such ascopper cables, fiber 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 OSImodel bridging acts in the first 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 traffic is managed differently. Abridge will only send traffic from one side to the other if it is going to a destination on the otherside. This is different to a layer 1 switch which sends all traffic from either side. Sometimesnetwork bridges are called layer 2 switches. Since they need to look at the contents of the trafficgoing 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 networkdevices. The term commonly refers to a multi-port network bridge that processes and routesdata at the data link layer (layer 2) of the OSI model. Switches receives a message from any deviceconnected to it and then transmits the message only to the device for which the message wasmeant. This makes the switch a more intelligent device than a hub (which receives a message andthen transmits it to all the other devices on its network). Switches may operate at one or morelayers of the OSI model, including data link and network. A device that operates simultaneouslyat 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 makingthem act as a single network segment. It has multiple input/output (I/O) ports, in which asignal introduced at the input of any port appears at the output of every port except the originalincoming. A hub works at the physical layer (layer 1) of the OSI model. A hub does not examineor manage any of the traffic that comes through it: any packet entering any port is rebroadcaston all other ports. It is barely aware of frames or packets and mostly operates on raw bits orsymbols. Consequently, due to the larger collision domains, packet collisions are more frequentin 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 classified as physical layer devices in the OSI model. At the physical layer, hubs supportlittle in the way of sophisticated networking. Hubs do not read any of the data passing throughthem and are not aware of their source or destination addressing. A hub simply receives incomingEthernet 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 levelor higher power, or onto the other side of an obstruction, so that the signal can cover longerdistances. In telecommunication,repeater can be ann analog device that amplifies an input signalregardless of its nature (analog or digital) or a digital device that amplifies, 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 notattempt to interpret the data being transmitted, they operate on the physical layer, the firstlayer of the OSI model. Repeaters are used to boost signals in coaxial and twisted pair cableand in optical fiber lines. An electrical signal in a cable gets weaker the further it travels, due toenergy dissipated in conductor resistance and dielectric losses. Similarly a light signal travelingthrough an optical fiber suffers attenuation due to scattering and absorption. In long cable runs,repeaters are used to periodically regenerate and strengthen the signal.
Created by
Amal, Nithish, Rakesh & Vishnu
17
Part II
Networking Technologies
19
3
Berkeley Socket
3.1 Berkeley Socket API
A socket API is an application programming interface (API), usually provided by the operatingsystem, 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) forinternet sockets and Unix domain sockets, used for inter-process communication (IPC). BerkeleySocket API is a networking API in C. It allows creation of sockets which acts as a standardinterface between network and application.
3.2 Header Files
The services of Berkeley Socket API is provided to application programmers through 5 headerflies. 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 pro-tocol families PF INET and PF INET6. Widely used on the Internet, these include IPaddresses and TCP and UDP port numbers.
3. < sys/un.h > PF UNIX/PF LOCAL address family. Used for local communication be-tween 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 ad-dresses. 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 ofnetwork implementation s can be used to facilitate communications. The functions provided bythe Berkeley sockets API library are:
21
CHAPTER 3. BERKELEY SOCKET
• socket() creates a new socket of a certain socket type, identified by an integer number, andallocates system resources to it. It returns a file descriptor for the socket. socket() takesthree arguments:
1. domain, which specifies the protocol family of the created socket.
2. type, one of:
– SOCK STREAM (reliable stream-oriented service or Stream Sockets)
– SOCK DGRAM (datagram service or Datagram Sockets)
– SOCK SEQPACKET (reliable sequenced packet service), or
– SOCK RAW (raw protocols atop the network layer).
3. protocol specifying the actual transport protocol to use. The most common are IP-PROTO TCP, IPPROTO SCTP, IPPROTO UDP, IPPROTO DCCP. These proto-cols are specified in ¡netinet/in.h¿. The value 0 may be used to select a default protocolfrom the selected domain and type.
• bind() assigns a socket to an address. When a socket is created using socket(), it is onlygiven a protocol family, but not assigned an address. This association with an addressmust be performed with the bind() system call before the socket can accept connections toother 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 field specifying the size of the sockaddr structure.
• listen() After a socket has been associated with an address, listen() prepares it for incomingconnections. However, this is only necessary for the stream-oriented (connection-oriented)data modes, i.e., for socket types (SOCK STREAM, SOCK SEQPACKET). listen() re-quires two arguments:
– sockfd, a valid socket descriptor.
– backlog, an integer representing the number of pending connections that can be queuedup 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, identified by its file descriptor, to aremote host specified by that host’s address in the argument list. Certain types of socketsare connectionless, most commonly user datagram protocol sockets. For these sockets,connect takes on a special meaning: the default target for sending and receiving datagets set to the given address, allowing the use of functions such as send() and recv() onconnectionless sockets.
• accept() When an application is listening for stream-oriented connections from other hosts,it is notified of such events (cf. select() function) and must initialize the connection usingthe accept() function. The accept() function creates a new socket for each connection andremoves 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 client’s address information.
22 Created by
Amal, Nithish, Rakesh & Vishnu
CHAPTER 3. BERKELEY SOCKET
– addrlen, a pointer to a socklen t location that specifies the size of the client addressstructure passed to accept(). When accept() returns, this location indicates how manybytes of the structure were actually used.
The accept() function returns the new socket descriptor for the accepted connection, or -1if an error occurs. All further communication with the remote host now occurs via thisnew socket. Datagram sockets do not require processing by accept() since the receiver mayimmediately respond to the request using the listening socket.
• send() and recv(), or write() and read(), or sendto() and recvfrom(), are used for sendingand receiving data to/from a remote socket.
• close() causes the system to release resources allocated to a socket. In case of TCP, theconnection is terminated.
• gethostbyname() and gethostbyaddr() The gethostbyname() and gethostbyaddr() functionsare used to resolve host names and addresses in the domain name system or the local host’sother resolver mechanisms (e.g., /etc/hosts lookup). They return a pointer to an objectof type struct hostent, which describes an Internet Protocol host. The functions take thefollowing arguments:
– name specifies the name of the host. For example: www.wikipedia.org
– addr specifies a pointer to a struct in addr containing the address of the host.
– len specifies the length, in bytes, of addr.
– type specifies 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 integerh errno may be checked to see whether this is a temporary failure or an invalid or unknownhost. 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 readyto 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 tosee 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 thespecified socket.
• setsockopt() is used to set a particular socket option for the specified socket.
3.4 Modes of Berkeley Sockets
Berkeley sockets can operate in one of two modes: blocking or non-blocking. A blocking socketwill not return control until it has sent (or received) some or all data specified for the operation.It is normal for a blocking socket not to send all data. The application must check the returnvalue to determine how many bytes have been sent or received and it must resend any data notalready processed. It also may cause problems if a socket continues to listen: a program mayhang as the socket waits for data that may never arrive. When using blocking sockets, specialconsideration should be given to accept() as it may still block after indicating readability if aclient disconnects during the connection phase.
Created by
Amal, Nithish, Rakesh & Vishnu
23
CHAPTER 3. BERKELEY SOCKET
On the other hand, a non-blocking socket will return whatever is in the receive buffer andimmediately continue. If not written correctly, programs using non-blocking sockets are particu-larly susceptible to race conditions due to variances in network link speed. A socket is typicallyset to blocking or nonblocking mode using the fcntl() or ioctl() functions.
24 Created by
Amal, Nithish, Rakesh & Vishnu
4
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, oneof the most important reasons for Java being the premier language for network programming arethe classes defined in java.net package. They provide an easy-to-use means by which programmersof all skill level can access network resources.
At the core of Java‘s networking support is the concept of a socket. A socket identifies anend point in a network.
4.2 Java.net Package
The java.net package provides a powerful and flexible infrastructure for networking. Figure 4.1shows the class hierarchy for this package.
Classes for Connection Oriented Communication
Connection Oriented communication is made possible by using TCP/IP protocol and classesthat support socket based communication based on TCP/IP protocol. These sockets are used toimplement reliable, bidirectional, persistent, point-to- point, stream-based connections betweenhosts on the Internet. A socket can be used to connect Javas I/O system to other programsthat may reside either on the local machine or on any other machine on the Internet. One is forservers, and the other is for clients. They are:
1. ServerSocketJava has a different socket class that is used for crating server applications. The Server-Socket class is used to create servers that listen for local or remote client programs toconnect to them on published ports. When a ServerSocket is created, it will register itselfwith the system as having an intrest in client connections. The constructor of Server-Socket class has the format ServerSocket(int port) throws IOException. ServerSocket hasa 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 withclient. ServerSocket class uses TCP/IP protocol for communication.
2. SocketThe Socket class is for clients and is designed to connect to ServerSocket and initiateprotocol exchanges. Creation of Socket object implicitly establishes a connection betweenclient 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 getInput-Stream() and getOutputStream().
Classes for Connection-less Communication
TCP/IP-style networking provides predictable and serialized, reliable stream of packet data. buthowever using TCP/IP tends to be inefficient as it requires a dedicated connection and severalother features like retransmission of lost data etc. Here Connection-less data communicationprovides an alternative. Connection-less communication is made possible by using UDP protocoland classes that can transport Datagrams from one machine to another without using a dedicatedconnection. Datagrams are bundles of information that are passed between machines. Javaimplements datagrams on top of UDP protocol by using two classes:
1. DatagramSocketDatagramSocket 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 first creates a DatagramSocket bound to any unused port on the local computer. Thesecond creates a DatagramSocket bound to port specified by port. The third creates aDatagramSocket bound to specified port and InetAddress while fourth constructs a Data-gramSocket bound to specified SocketAddress. Two most important method defined byDatagramSocket class are send() and receive(). send() method sends packet to the portspecified by packet while receive() method waits for a packet to be received from the portspecified by packet.
void send(DatagramPacket packet) throws IOException
void receive(DatagramPacket packet) throws IOException
2. DatagramPacketDatagram Packet represents the packets which are used to send information between sys-tems. These packets can store information as binary array. DatagramPackets constructedto send information contains the receiver address represented by InetAddress class. Data-gramPacket defines several constructors.
• DatagramPacket(byte data[ ], int size)
Created by
Amal, Nithish, Rakesh & Vishnu
27
CHAPTER 4. NETWORKING IN JAVA
• DatagramPacket(byte data[ ], int offset, int size)
• DatagramPacket(byte data[ ], int size, InetAddress ipAddress, int port)
• DatagramPacket(byte data[ ], int offset, int size, InetAddress ipAddress, int port)
The first constructor specifies a buffer that will receive data, and the size of a packet. It isused for receiving data over a DatagramSocket. The second form allows you to specify anoffset into the buffer at which data will be stored. The third form specifies a target addressand port, which are used by a DatagramSocket to determine where the data in the packetwill be sent. The fourth form transmits packets beginning at the specified offset into thedata.
Other Important Classes in java.net package
1. InetAddressThe InetAddress class represents an Internet Protocol (IP) address and can be used whencreating DatagramPacket or Socket objects. The class does not have public constructorfunctions. Instead it supports three static methods which return one or more instances ofInetAddress. The InetAddress class contains two fields namely, hostName (of type Stringobject) and address (of type int) which are not public. The hostName field contains thename of host and the address field contains the 32 bit IP address, for e.g.. 140.105.16.63(this is IPv4. This representation will be different for a 16 byte IPv6 address). ThegetLocalHost(), getByName() and getAllByName() methods must be used by applicationsto 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 virtualmachine to invoke methods on an object in another Java virtual machine. Any object that canbe invoked this way must implement the Remote interface. When such an object is invoked, itsarguments are “marshalled” and sent from the local virtual machine to the remote one, where thearguments are “unmarshalled.” When the method terminates, the results are marshalled fromthe remote machine and sent to the caller’s virtual machine. If the method invocation results inan exception being thrown, the exception is indicated to caller.
Classes of Java.rmi Package
1. MarshalledObjectA MarshalledObject contains a byte stream with the serialized representation of an objectgiven to its constructor. The get method returns a new copy of the original object, as dese-rialized from the contained byte stream. The contained object is serialized and deserializedwith the same serialization semantics used for marshaling and unmarshaling parametersand 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. NamingThe Naming class provides methods for storing and obtaining references to remote objectsin the remote object registry. The Naming class’s methods take, as one of their arguments,a name that is a URL formatted String of the form //host:port/name where host is thehost (remote or local) where the registry is located, port is the port number on which theregistry 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. Ifport is omitted, then the port defaults to 1099, the well-known port that RMI’s registry,rmiregistry, uses. The bind() method of Naming class binds the specified name to a remoteobject. Syntax of bind() method is as follows:
public static void bind(String name, Remote obj)throws AlreadyBoundException, Mal-formedURLException, RemoteException
3. RMISecurityManager RMISecurityManager provides an example security manager foruse by RMI applications that use downloaded code. RMI’s class loader will not downloadany classes from remote locations if no security manager has been set. RMISecurityMan-ager does not apply to applets, which run under the protection of their browser’s securitymanager. RMISecurityManager class provide a public no argument constructor to produceobjects.
Interfaces of Java.rmi Package
1. RemoteThe Remote interface serves to identify interfaces whose methods may be invoked from anon-local virtual machine. Any object that is a remote object must directly or indirectlyimplement this interface. Only those methods specified in a “remote interface”, an interfacethat extends java.rmi.Remote are available remotely. Implementation classes can imple-ment any number of remote interfaces and can extend other remote implementation classes.RMI provides some convenience classes that remote object implementations can extendwhich facilitate remote object creation. These classes are java.rmi.server.UnicastRemoteObjectand java.rmi.activation.Activatable.
4.4 Java.sql Package
JDBC is a Java-based data access technology which provides methods for querying and updatingdata in a database. This technology is an API for the Java programming language that defineshow a client may access a database. The classes that makes up the Application ProgrammingInterface of JDBC technology are contained in the Java.sql package. Java.sql package constitutesan API providing a framework which allows different drivers to be installed dynamically to accessdifferent data sources. Although the JDBC API is mainly geared to passing SQL statementsto a database, it provides for reading and writing data from any data source with a tabularformat. 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, flat file, or any other tabulardata source.
Classes of Java.sql Package
1. DriverManagerThis class provides the basic services for managing a set of JDBC drivers. As part of its
Created by
Amal, Nithish, Rakesh & Vishnu
29
CHAPTER 4. NETWORKING IN JAVA
initialization, the DriverManager class will attempt to load the driver classes referencedin the ”jdbc.drivers” system property. This allows a user to customize the JDBC Driversused by their applications. The most important method of DriverManager class is thegetConnection(). 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 SQLEx-ception
The getConnection() method attempts to establish a connection to the given databaseURL. The DriverManager attempts to select an appropriate driver from the set of registeredJDBC drivers.
Interfaces of Java.sql Package
1. ConnectionThe Connection interface describes a connection(session) with a specific database. It allowsSQL statements to be executed and results to be returned within the context of a connec-tion. The most important method provided by this interface is the createStatement(). ItsSyntax is described below.
Statement createStatement()
The createStatement() creates a Statement object for sending SQL statements to thedatabase.
2. ResultSetThe ResultSet interface represents a table of data representing a database result set, whichis usually generated by executing a statement that queries the database. A ResultSet objectmaintains a cursor pointing to its current row of data. Initially the cursor is positionedbefore the first row. The next() method moves the cursor to the next row, and because itreturns false when there are no more rows in the ResultSet object. The ResultSet interfaceprovides getter methods (getBoolean, getLong, and getString) for retrieving column valuesfrom 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. StatementThe Statement interface describes an object used for executing a static SQL statement andreturning 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 singleResultSet object while executeUpdate() method Executes the given SQL statement, whichmay be an INSERT, UPDATE, or DELETE statement or an SQL statement that returnsnothing, such as an SQL DDL statement.
30 Created by
Amal, Nithish, Rakesh & Vishnu
5
Java Server Pages
5.1 Introduction to JSP
JavaServer Pages (JSP) is a technology that helps software developers create dynamically gen-erated 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 compatibleweb server with a servlet container, such as Apache Tomcat, is required. A discussion about JSPwould be incomplete without an overview about Java servlets because JSP can be viewed as ahigh-level abstraction of Java servlets.
A Servlet is a Java-based server-side web technology. Technically speaking, a Servlet is aJava class that conforms to the Java Servlet API, a protocol by which a Java class may respondto requests. Servlets could in principle communicate over any clientserver protocol. JSPs aretranslated into servlets at runtime. Each JSP’s servlet is cached and re-used until the originalJSP is modified.
JSP allows Java code to be embedded within html code in a JSP page so that certain pre-defined actions can be interleaved with static web markup content, with the resulting page beingcompiled and executed on the server to deliver a document. The compiled pages, as well as anydependent Java libraries, use Java byte-code rather than a native software format. Like anyother Java program, they must be executed within a Java virtual machine (JVM) that integrateswith the server’s 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 ofOutputStream, 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 documentsdynamically. JSPs are run in sever side components known as JSP containers, which translatesthem 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 arepersistent 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 programmingpossible.
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 textfile with .jsp extension, and contains a mix of HTML template code, Java language state-ments, and JSP directives and actions that describe how to generate a Web page to servicea particular request.
2. Java Source Code The JSP container translates the JSP source code into the source codefor an equivalent Java servlet as needed. This source code os typically saved in a work areaand is often helpful for debugging.
3. Compiled Java class Like any other Java class, the generated servlet code is compiledinto byte codes in a .class file, ready to be loaded and executed.
The JSP container manages each of these forms of JSP page automatically, based on the times-tamp of each file. In response to an HTTP request, the container checks to see if the .jsp sourcehas been modified since the .java source was last compiled. If so, the container retranslates theJSP source code into Java source and recompiles it. When a request for JSP page is made, thecontainer first determines the name of the class corresponding to .jsp file. If class doesn’t exitsor is older than .jsp file, then the container creates java source code for equivalent servlet andrecompiles it. Then the container loads the servlet class and creates an instance. Finally thecontainer 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 file can contain JSP elements, fixed template data, or any combination of the two. JSPelements are instructions to the JSP container about what code to generate and how it shouldoperate. these elements have specific 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 datais passes through unmodified, so the HTMl that is ultimately generated contains the templatedata 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. Theyhave 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 followingsyntax:
< %@ 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 file at translation time into the .jsp sourceinput stream, much like a #include C preprocessor directive. The syntax is
< %@ include file = “filename“ % >
where filename is an absolute or relative pathname interpreted according to the current servletcontext.
The taglib Directive
The taglib directive makes custom actions available in the current page through the use of a taglibrary. The syntax of the directive is
< %@ taglib uri = “tagLibraryURI“ prefix = “tagPrefix“ % >
where tagLibrary is the URL of a Tag Library Descriptor and URI tagPrefix is a unique prefixused to identify custom tags used later in the page.
Created by
Amal, Nithish, Rakesh & Vishnu
33
CHAPTER 5. JAVA SERVER PAGES
Scripting elements
Expressions
JSP provides a simple means for accessing the value of a Java variable or other expression andmerging 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 itcan 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 anHTTP 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 areeach appended to the jspService() method in the order in which they are coded. This beingthe 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 difference: script-let code becomes part of the jspService() method, whereas declaration code is incorporatedinto the generated source file outside the jspService() method. The syntax of a declarationsection is
< %! statement; [statement; ...]% >
Actions
Actions are high-level JSP elements that create, modify, or use other objects. Unlike directivesand scripting elements, actions are coded using strict XML syntax
< tagname [attr = ”value”attr = ”value” ...] > ... < /tag − name >
or, if the action has no body, an abbreviated form:
< tagname [attr = ”value”attr = ”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
6
Extended Markup Language
6.1 What is XML
Extensible Markup Language or shortly XML is simply a set of rules used to impose structureand syntax on plain text. XML allows hierarchical and structured data to be represented withease. XML is a subset of Standard General Markup Language (SGML) and is defined in XML1.0 Specification produced by the W3C. XML defines a set of rules for encoding documents in aformat that is both human-readable and machine-readable. It allows creating documents that areplatform 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 tagscan be nested indefinitely allowing XML to represent highly complex and hierarchical data withease. Similar to HTML documents, XML documents can be created in a text editor, such asNotepad which can be then saved in .xml extension. Unlike HTML which have predeterminedtags, XMLs tags are user defined and hence XML is highly extensible. XML documents areprocessed 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 specifies that the document is an XML document. It is technicallyoptional, but recommended in most normal cases.
2. A document type declaration that refers to a DTD (which is optional, but required if youwant 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 usedto indicate that the specified document is an XML document. The XML declaration statementincludes a keyword, xml, preceded by a question mark (?). This statement includes the XMLspecification to which the XML document adheres. For example, if the XML document thatyou create is based on XML Specification 1.0, then the XML declaration statement would be asshown here:
<?xml version = ”1.0”? >
Markup Syntax
Components, such as declaration statements or markup tags, define the syntax for creating anXML document. The syntax used to create an XML document is called markup syntax. Themarkup syntax is used to define the structure of the data in the document. The markup syntaxincludes all tags, DOCTYPE declaration statements, comments, DTDs, and character references.
Document Type Definitions
XML allows creation of custom tags. However, when a structured document is created, thestructure needs to be conveyed to the users who use the XML document. This can be doneusing Document Type Definitions (DTDs). A DTD is a vocabulary that defines the structureand elements in an XML document. An XML document that has a DTD attached to it is calleda valid XML document. This implies that a valid XML document is both syntactically correctand conforms to the rules of vocabulary as described in a DTD. To use a DTD with an XMLdocument, the DTD needs to be associated with the XML document . To do this, the DOCTYPEdeclaration 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 Doctypedeclaration statement might include the markup declaration statement as a subset. The markupdeclaration statements, which are included as a subset of the Doctype declaration statement, arecalled internal DTD subset. The syntax of the Doctype declaration statement is as shown:
<!DOCTY PE name [markup statements] >
Similarly, an external DTD can also be included in the XML document. To do this, the sourceand path of the external DTD is include in the doctype declaration statement. The path ofa DTD is the URL of the .dtd file. The DTD statement also includes a keyword, which canbe either SYSTEM or PUBLIC. The SYSTEM keyword denotes that the markup declarationstatements are directly included in the .dtd file present at the specified URL. The PUBLICkeyword denotes that the DTD to be included is a well-known vocabulary in the form of a localcopy of the .dtd or .dtd file placed in a database server.
XML Entities
In addition to the markup syntax, an XML document consists of the content or data to bedisplayed. The content of the XML file is the data enclosed within tags. The data stored in anXML 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 defined in the UnicodeCharacter Set. The following example shows the text data in an XML document:
< Employee Name > John Smith < /Employee Name >
Comments
Another important component of an XML document is comment entries. Comments allow youto include instructions or notes in an XML document. These comments help you to provide anymetadata about the document to the users of the document. Any data that is not part of themain 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 containersthat contain XML data, such as text, text references, entities, and so on. You can also includeelements within another element. This implies that you can have nested elements. The contentwithin an element is called the element content. It is essential that you enclose all XML datawithin elements. All elements include starting and ending tags. However, if an elements has nocontent, an empty element can be created. Empty elements can be written in an abbreviatedform. the syntax of an empty element is
< Element Name/ >
Attributes
Attributes are used to specify properties of an element. An attribute has a value associated withit. In the preceding code, the keyword color is an attribute of the element apple, and the valueassigned to the color attribute is red. Attributes allow you to provide additional information inan XML document. The value of an attribute is assigned to it by using the equal sign (=), andit is enclosed within double quotes (”) as shown.
< Element Name Attribute Name1 = value [Attribute; Name2 = value]... >
All the attributes that can be declare for an element can included in a DTD. A DTD containsthe ATTLIST tag that includes the attribute declaration statement for each attribute. You caninclude multiple attribute definitions in one ATTLIST tag. However, to avoid confusion, it isadvisable to include a different AATLIST tag for each attribute. The syntax for the ATTLISTtag is as shown:
<!ATTLIST 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 shorthand notation.
Created by
Amal, Nithish, Rakesh & Vishnu
37
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 withinthe root element.
5. Attribute values must always be quoted.
6.5 Advantages of using XML
XML because of its SGML foundation, is flexible enough to work for any situation that requiresthe formatting of structured data. Any information that can be stored in a spreadsheet ordatabase type structure can be stored within an XML document. XML document have verystrict sidelines that must be followed in order for them to be read by the variety of parsingand validating software available for use with XML documents on the internet. Documentsthat meet the requirements are termed well-formed, having followed all of the rules for creatingXML documents and applications. XML is highly extensibility and has a universal format. Soit is widely used for data exchange between applications and networks. XML allows creationof custom tags based on the requirements of a document. Therefore, they can be used as avocabulary for all related documents. The simplicity offered by XML allows it to be easy tounderstood and used. The organization abilities XML allows structuring even complex dataand seamless building of platform by segmenting the design process. Separation of data andformatting rules simplifies the development process. XML is an international standard. Thisimplies that an XML document can be processed by all application s with ease. Highly extensibleproperty of XML in form of creating DTDs and personalized tags allows it be used for all typesof applications with ease. XML allows structured data transportation and handling easy.
38 Created by
Amal, Nithish, Rakesh & Vishnu
7
Applets
7.1 Java Applet
Applets are small applications that are accessed on an Internet server, transported over theInternet, automatically installed, and run as part of a Web document. Applet is a client sidetechnology as far as networking is concerned. After an applet arrives on the client, it has limitedaccess to resources, so that it can produce an arbitrary multimedia user interface and run complexcomputations without introducing the risk of viruses or breaching data integrity.
Java Applets can provide web applications with interactive features that cannot be providedby HTML. Since Java’s bytecode is platform-independent, Java applets can be executed bybrowsers running under many platforms, including Windows, Unix, Mac OS, and Linux. Whena Java technology-enabled web browser processes a page that contains an applet, the applet’scode is transferred to the client’s system and executed by the browser’s Java Virtual Machine(JVM). An HTML page references an applet either via the deprecated < APPLET >
7.2 Capabilities of an Applet
Applets can capture mouse input and also have controls like buttons or check boxes. In responseto the user action an applet can change the provided graphic content. This makes applets wellsuitable for demonstration, visualization and teaching. Applets can also play media in formatsthat are not natively supported by the browser.
HTML pages may embed parameters that are passed to the applet. Hence the same appletmay appear differently depending on the parameters that were passed.
Java applets are executed in a sandbox by most web browsers, preventing them from accessinglocal data like clipboard or file system. The code of the applet is downloaded from a web serverand the browser either embeds the applet into a web page or opens a new window showing theapplet’s user interface. A Java applet extends the class java.applet.Applet, or in the case of aSwing applet, javax.swing.JApplet. The class must override methods from the applet class toset up a user interface inside itself (Applet) is a descendant of Panel which is a descendant ofContainer. As applet inherits from container, it has largely the same user interface possibilitiesas an ordinary Java application, including regions with user specific 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 crossplatform. Applets are supported by most web browsers.
• The same applet can work on ”all” installed versions of Java at the same time, rather thanjust 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 first applet is run, the JVM is already running andstarts 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 scalablewith the number of users/clients.
• If a standalone program (like Google Earth) talks to a web server, that server normallyneeds to support all prior versions for users which have not kept their client softwareupdated. In contrast, a properly configured browser loads (and caches) the latest appletversion, so there is no need to support legacy versions.
• The applet naturally supports the changing user state, such as figure positions on thechessboard.
• Developers can develop and debug an applet direct simply by creating a main routine(either in the applet’s class or in a separate class) and calling init() and start() on theapplet, 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 itcame from. This makes such an applet much safer to run than a standalone executablethat it could replace. However, a signed applet can have full access to the machine it isrunning 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 ofinterrupt service routines. An applet waits until an event occurs. The Abstract Window Toolkit(AWT) notifies the applet about an event by calling an event handler that has been provided bythe applet. Once this happens, the applet must take appropriate action and then quickly returncontrol to the AWT. An applet must perform specific actions in response to events and thenreturn control to the AWT run-time system. The user initiates interaction with an applet. theuser interacts with the applet as and when they wants. These interactions are sent to the appletas events to which the applet must respond.
The basic mechanism by which the browser or applet viewer interfaces to the applet andcontrols its execution are Four methodsinit( ), start( ), stop( ), and destroy( )defined by Appletclass in Java.applet package and paint( ) defined by the AWT Component class. These methodsare described below.
40 Created by
Amal, Nithish, Rakesh & Vishnu
CHAPTER 7. APPLETS
init( )
The init( ) method is the first 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 beenstopped. Whereas init( ) is called oncethe first time an applet is loadedstart( ) is called each timean applets HTML document is displayed onscreen. So, if a user leaves a web page and comesback, the applet resumes execution at start( ).
stop( )
The stop( ) method is called when a web browser leaves the HTML document containing theappletwhen it goes to another page, for example. When stop( ) is called, the applet is probablyrunning. You should use stop( ) to suspend threads that dont need to run when the applet isnot 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 beremoved completely from memory. At this point, you should free up any resources the appletmay 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 situationcan occur for several reasons. For example, the window in which the applet is running may beoverwritten by another window and then uncovered. Or the applet window may be minimizedand 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 oneparameter of type Graphics. This parameter will contain the graphics context, which describesthe graphics environment in which the applet is running. This context is used whenever outputto 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 appletviewer. Web browsers allow many applets on a single page. The syntax for the standard AP-PLET tag is shown here. Square bracketed items are optional.
Created by
Amal, Nithish, Rakesh & Vishnu
41
CHAPTER 7. APPLETS
< APPLET
[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 specifies the base URL of the applet code.CODE CODE is a required attribute that gives the name of the file containing your appletscompiled .class file.ALT The ALT tag is an optional attribute used to specify a short text message that should bedisplayed 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. Appletsmust be named in order for other applets on the same page to find them by name and commu-nicate with them.ALIGN ALIGN is an optional attribute that specifies the alignment of the applet.VSPACE AND HSPACE These attributes are optional. VSPACE specifies the space, inpixels, above and below the applet. HSPACE specifies the space, in pixels, on each side of theapplet.PARAM NAME AND VALUE The PARAM tag allows you to specify applet- specific ar-guments in an HTML page. Applets access their attributes with the getParameter( ) method.
42 Created by
Amal, Nithish, Rakesh & Vishnu
Part III
Experiments
43
8
Connecting Two Computers
Description
This experiment requires connecting two computers using a Ethernet cable or LAN cable so thatdata can be shared between them. This is primarily done so that programs which illustratesnetworking technologies can be illustrated by running server program (a peer program) in onemachine 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 ofthe 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 Con-nection Status.
c) In this newly opened Window, Click on properties.This will open Local Area Connec-tion Properties window.
d) In the list Appearing in the Local Area Connection Properties Window, select InternetProtocol Version 4 and click on properties.
e) In the newly opened window select Use the following IP address and fill in the follow-ing detailsIP address= The IP Address we intended to give the machineSubnet Mask=255.255.255.0Default 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 currentlyconnected 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 fill in following details.Address= The IP Address we intended to give the machineNet Mask=255.255.255.0Gateway=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 verified by using ping command by giving other machines IPaddress 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 asmachine 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 com-mand.
Created by
Amal, Nithish, Rakesh & Vishnu
47
9
Berkeley Socket
Description
Here, in this experiment, we have created a client program which communicate with serverprogram. The server reverses the string sent by client and sends it back.
Algorithm
Algorithm BerkeleyServerbegin
Step 1: Start ServerStep 2: Wait for a connect request from the clientStep 3: Accept the connection requestStep 4: Read a message from clientStep 5: Find reverse of message and store it on reverse mesageStep 6: Send the reverse message back to clientStep 7: Goto Step 2
end
Algorithm BerkeleyClientbegin
Step 1: Start ClientStep 2: Connect to serverStep 3: Read a message from userStep 4: Send the message to the serverStep 5: Read a message from serverStep 6: Print the messageStep 7: Stop
end
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
Amal, Nithish, Rakesh & Vishnu
51
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
Amal, Nithish, Rakesh & Vishnu
53
10
Echo Server
Description
A server program that supports Echo Protocol is generally called as an Echo Server. In thisprotocol the server sends back an identical copy of the data it received back to the client thatsend them as soon as it is received. In the following sections of this chapter, we describe animplementation of a server that implements Echo Protocol. The implementation contains a servercapable of accepting connection requests of multiple clients at same time. After connecting, serverwaits 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 datait sends to the server.
Algorithm
Algorithm EchoServerbegin
Step 1: Start ServerStep 2: Do Step 3 and 6 in parallelStep 3: Wait for a connect request from the clientStep 4: Accept the connection requestStep 5: Goto Step 3Step 6: For each connected client, do Step 7 to 8 repeatedlyStep 7: Read a message from clientStep 8: Send the same message back to clientStep 9: Stop
end
Algorithm EchoClientbegin
Step 1: Start ClientStep 2: Connect to serverStep 3: Read a message from user
55
CHAPTER 10. ECHO SERVER
Step 4: Send the message to the serverStep 5: Read a message from serverStep 6: Print the messageStep 7: If message is not ‘bye’ Goto Step 3Step 8: Stop
end
Program
import java.awt.event .*;import java.awt .*;import java.net .*;import 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
Amal, Nithish, Rakesh & Vishnu
57
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
Amal, Nithish, Rakesh & Vishnu
59
11
Chatting
Description
Chatting may be refer to any kind of communication that offers a real-time direct transmissionof text-based messages from sender to receiver. A chatting system consist of a central servercalled chat server and many clients that connect to the server. The server addresses each clientsby some predefined method. Direct communication is only allowed between server and client. Inthis system a client sends a packet containing the recipient (another client) address and messagecontent to the server. The server unpacks this packet and identifies the recipient of the message.The message along with the senders address is then forwarded to the intended recipient. In thefollowing section of this chapter, we describe an implementation of a chatting system consisting ofa chat server which is capable of serving multiple clients at same time. A general implementationof a client is also described.
Algorithm
Algorithm ChatServerbegin
Step 1:Start the serverStep 2:Do Step 3 and 7 in parallelStep 3:Wait for connect request from clientStep 4:If maximum client capacity has not reached accept the client connectionStep 5:Read the name of the clientStep 6:Goto Step 3Step 7:For all connected clients do steps 8 to 10 repeatedlyStep 8:Read data from clientStep 9:Separate client name and message from dataStep 10:Send message to the client with name client nameStep 11:Stop
end
Algorithm ChatClientbegin
61
CHAPTER 11. CHATTING
Step 1: Start ClientStep 2: Connect to serverStep 3: Send name of the client to the serverStep 4: Do Step 4 and 8 in parallelStep 5: Wait for a message from ServerStep 6: Print the messageStep 7: Goto Step 5Step 8: Read the client name to which message is to be sent from userStep 9: Read the message to be sent from userStep 10: Sent the client name and message to serverStep 11: If message is not ‘bye’ Goto Step 8Step 12: Stop
end
Program
import java.net .*;import java.awt .*;import java.io.*;import 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 voidwindowClosing(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
Amal, Nithish, Rakesh & Vishnu
63
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
Amal, Nithish, Rakesh & Vishnu
65
12
File Server
Description
Downloading means to receive data to a local system from a remote system. A server programthat allows connected clients to download files which is stored in its local storage is called a FileServer. A file server may have ability to serve multiple clients. In the following sections of thischapter, we describe an implementation of File server which can serve multiple clients at sametime. The client ones connected can send the name of a required file to the server. If the file isin the local storage of the server, the server asks for the name in which the file is to be save inthe clients storage. Ones the name is received, the server initiates a file transfer with the client.At the end of the transfer, client receives an identical copy of the file in the server. Thus theclient downloads the file.
Algorithm
Algorithm FileServerbegin
Step 1:Start the serverStep 2:Do Step 3 and 6 in parallelStep 3:Wait for connect request from clientStep 4:If maximum client capacity has not reached accept the client connectionStep 5:Goto step 3Step 6:For all connected clients do steps 7 to 9 repeatedlyStep 7:Read filename from clientStep 8:Read the data in the fileStep 9:Send the data to the clientStep 10:Stop
end
Algorithm FileClientbegin
Step 1: Start ClientStep 2: Connect to server
67
CHAPTER 12. FILE SERVER
Step 3: Read the name of the file to be downloaded from user into a variable dw file nameStep 3: If dw file name is ‘bye’ Goto Step 12Step 5: Read the name in which the file is to be saved from user into a variable sav nameStep 4: Send dw file name to the serverStep 6: Create a new file with name sav nameStep 5: Read the data coming from serverStep 7: Write this data to the opened fileStep 5: Save the fileStep 8: Goto Step 3Step 12: Stop
end
Program
import java.awt.event .*;import java.awt .*;import java.net .*;import 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
Amal, Nithish, Rakesh & Vishnu
69
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
Amal, Nithish, Rakesh & Vishnu
71
13
UDP Messaging
Description
In this chapter we describe a system which allows simple messages to be sent between two clientsdirectly without a need for a central server. The messages are sent using User Datagram Protocolby constructing Datagram packets containing message and the receivers address. The intentionof this chapter is to illustrate usage of UDP protocol. In the following sections, we have describedan implementation of a simple client capable of sending message to another client and capableof receiving messages sent to it using UDP protocol.
Algorithm
Algorithm UDPSenderRecieverbegin
Step 1:Start the programStep 2:Do Step 3 and 8 in parallelStep 3:Wait until a Datagram Packet arrives at the port in which the program is boundStep 4:Receive the Datagram PacketStep 5:Extract the payload to messageStep 6:Print messageStep 7:Goto Step 3Step 8:Read Receivers address and message from userStep 9:If message is ‘bye’ Goto Step 13Step 10:Create datagram packet with Receivers address as address and message as Pay-loadStep 11:Sent this datagram PacketStep 12:Goto Step 8Step 13:Stop
end
73
CHAPTER 13. UDP MESSAGING
Program
import java.net .*;import java.awt .*;import java.io.*;import 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
Amal, Nithish, Rakesh & Vishnu
75
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. Incomputer networking, broadcasting refers to transmitting a packet that will be received by ev-ery device on the network. In this chapter, we describe an implementation of a server whichbroadcasts a specific message to all the clients connected to it. The server is capable of handlingmultiple clients at a time. A simple implementation of the client is also described.
Algorithm
Algorithm BroadcastServerbegin
Step 1: Start the serverStep 2: Read a line from userStep 3: Send this line to all connected clientsStep 4: Goto Step 2
end
Algorithm BroadcastClientbegin
Step 1: Connect to the serverStep 2: Receive message coming from serverStep 3: Print the messageStep 4: Goto Step 2
end
Program
77
CHAPTER 14. BROADCASTING
import java.net .*;import java.awt .*;import java.io.*;import 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 voidwindowClosing(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 broadcast_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
Amal, Nithish, Rakesh & Vishnu
79
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 pro-gram to cause a subroutine or procedure to execute in another address space (commonly onanother computer on a shared network) without the programmer explicitly coding the detailsfor this remote interaction. That is, the programmer writes essentially the same code whetherthe subroutine is local to the executing program, or remote. When the software in question usesobject-oriented principles, RPC is called remote invocation or remote method invocation.RMIis the Java version of a remote procedure call (RPC), but with the ability to pass one or moreobjects along with the request.
An RPC is initiated by the client, which sends a request message to a known remote serverto execute a specified procedure with supplied parameters. The remote server sends a responseto 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 finished 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 pushedon to the stack in the normal way.
2. The client stub packs the parameters into a message and makes a system call to send themessage. Packing the parameters is called marshaling.
3. The client’s local operating system sends the message from the client machine to the servermachine.
4. The local operating system on the server machine passes the incoming packets to the serverstub.
5. The server stub unpacks the parameters from the message . Unpacking the parameters iscalled unmarshaling.
6. Finally, the server stub calls the server procedure. The reply traces the same steps in thereverse direction.
81
CHAPTER 15. REMOTE METHOD INVOCATION
Algorithm
Algorithm Remote Method Invocationbegin
// The four source files used are://AddServerIntf.java defines 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 codesThis will create files AddClient.class, AddServerIntf.class, AddServerImpl.class,AddServer.classStep 2 :Generate a Stub using RMI compiler.This will create file AddServerImpl Stub.classStep 3 :Install files on client and server machinesCopy AddClient.class, AddServerImpl Stub.class, and AddServerIntf.class to adirectory on the client machine.Copy AddServerIntf.class, AddServerImpl.class, AddServerImpl Stub.class, andAddServer.class to a directory on the server machine.Step 4 :Start RMI registry on the Server MachineStep 5 :Start the ServerStep 6 :Start the Client
end
Program
import java.net .*;import java.rmi .*;import java.rmi.server .*;import 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
Amal, Nithish, Rakesh & Vishnu
83
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 program-ming language that defines how a client may access a database. It provides methods for queryingand updating data in a database. JDBC is oriented towards relational databases. The API pro-vides a mechanism for dynamically loading the correct Java packages and registering them withthe JDBC Driver Manager. The Driver Manager is used as a connection factory for creatingJDBC connections.
Algorithm
Algorithm DatabaseConnectionbegin
//We have a database table Student with following schema Student[Sl no,Name,Mark1,Mark2,Mark3]Step 1 : Load and register JDBC driverStep 2 : Create a connection to the databaseStep 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 userStep 10 : if choice is 4 goto step 25Step 11 : if choice is 3 goto step 21Step 12 : if choice is 2 goto step 17Step 13 : Read name, mark1, mark2,mark3 from userStep 14 : Create a query for insertion with these detailsStep 15 : Execute queryStep 16 : goto step 3Step 17 : Read name, new mark1, new mark2,new mark3 from userStep 18 : Create a query for update marks of name with new mark1,new mark2,new mark3
85
CHAPTER 16. JAVA DATABASE CONNECTIVITY
Step 19 : Execute queryStep 20 : goto step 3Step 21 : Create a query for select the class detailsStep 22 : Execute query and store the data in resultStep 23 : Display the resultStep 24 : goto step 3Step 25 : Stop
end
Program
/* SQLcreate 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; jdbcclass 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
Amal, Nithish, Rakesh & Vishnu
87
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 files are used to transport structured data across network. In this chapter we have con-structed an XML file containing syllabus of a subject and created a corresponding XML StylesheetLanguage file which describes formatting of elements for the XML document. Finally the XMLfile 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: 500px;height: 540px;margin: auto;border :3px solid rgb
(209, 209, 209);"><div style="width :500px;height :50px;background -color: rgb(209, 209,
209);text -align:center;"><span style="font -size :20px;line -height :50px">
<xsl:value -of select="syllabus/subject"/></span >
</div ><div style="width :500px;height :30px;background -color: white;">
<span style="font -size :20px;line -height :30px">Subject Code: <xsl:value -of select="syllabus/code"/>
</span ></div ><xsl:for -each select="syllabus/module">
<div style="width: 500px;height: 150px;"><div style="width :500px;height :20px;background -color: rgb
(209, 209, 209);"><span style="font -size :18px;line -height :20px">
Module Name:<xsl:value -of select="name"/></span >
</div ><xsl:for -each select="topic">
<div style="width :500px;height :20px;"><span style="font -size :18px;line -height :20px">
<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
Amal, Nithish, Rakesh & Vishnu
91
18
Java Server Pages
Description
JSP is a java based server technology that can create dynamic web pages. It allows embeddingjava code within static webpage content and hence bring the power of java language into serverside processing. In the following section of this chapter we describe a creation of a JSP page thatwhen 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 bookentered 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
Amal, Nithish, Rakesh & Vishnu
95
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
Amal, Nithish, Rakesh & Vishnu
97
19
Java Applet
Description
A Java applet is an applet delivered to users in the form of Java bytecode. Java applets can runin a Web browser using a Java Virtual Machine (JVM), or in Sun’s AppletViewer, a stand-alonetool for testing applets. Java applets run at very fast speeds than JavaScript. In addition theycan use 3D hardware acceleration that is available from Java. This makes applets well suited fornon-trivial, computation intensive visualizations to web based applications entirely computed inthe client side. In this Chapter we describe creation of an applet which can draw a circle andthen daw a continuously revolving tangent to the circle. This result can be displayed in a webbrowser 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 tan−1(Lr )
//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 programStep 2: Set θ:=0Step 3: θ:=θ+1Step 4: x1:=
√L2 + r2 ∗ cos(θ)
Step 5: y1:=√L2 + r2 ∗ sin(θ)
Step 6: x2:=√L2 + r2 ∗ cos(θ + tan−1(L
r ))
Step 7: y2:=√L2 + r2 ∗ sin(θ + tan−1(L
r ))Step 8: drawCircle(r,xc,yc)Step 9: drawLine(x1,y1,x2,y2)
99
CHAPTER 19. JAVA APPLET
Step 10: Goto Step 3Step 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
Amal, Nithish, Rakesh & Vishnu
101
20
HTTP Server
Description
In this Experiment we tried to create a simple HTTP server program in java. This java programstarts running and binds itself to a predefined port. From this state onwards it listens to theport for http connection requests from client. After accepting connection requests it responds tothe request but responding with the resource client has requested. The server only acknowledgesrequest for plain html files or plain text files.
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 () + " isconnected");
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 QueryresponseBuffer.append(requestString + "<BR>");System.out.println(requestString);requestString = inFromClient.readLine ();
}if (httpMethod.equals("GET")) {
if (httpQueryString.equals("/")) {//no resource isrequested
String header="<b>Parameters of the HTTP Request </b></br>";
sendResponse (200, header+responseBuffer.toString (),false);
}else {
//This is interpreted as a file nameString 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";
elsestatusLine = "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
Amal, Nithish, Rakesh & Vishnu
105
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.htmland <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 <ahref="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 <ahref="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
Amal, Nithish, Rakesh & Vishnu
107
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
Amal, Nithish, Rakesh & Vishnu
109
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
Amal, Nithish, Rakesh & Vishnu
111
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 programhas the capability to send HTTP page requests for a URL. The program prints the result itreceives 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 manyother operating system. This command is used to test the ability of the source computer toreach a specified destination computer. The ping command is usually used as a simple wayverify that a computer can communicate over the network with another computer or networkdevice. Ping command works by sending echo requests to destination computer and seeing ifdestination computer responds back or not. The Standard ping command supplies much moreinformation like round trip time. In this experiment we have tried to implement an limited pingcommand which can test wether a destination computer can be reached or not.
Algorithm
Algorithm Pingbegin
Step 1:Start the programStep 2:Start timerStep 3:Send an echo request to source computerStep 4:Wait till source computer respondsStep 5:Stop the timer when Echo request is acknowledgedStep 6:Print the value of timerStep 7:Stop
end
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
Amal, Nithish, Rakesh & Vishnu
117
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 O’Donahue 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