Free Essay

Technology

In:

Submitted By reddys
Words 14996
Pages 60
Jan Graba

An Introduction to Network
Programming
with Java
Java 7 Compatible
Third Edition

An Introduction to Network Programming with Java

Jan Graba

An Introduction to Network
Programming with Java
Java 7 Compatible
Third Edition

Jan Graba
Department of Computing
Sheffield Hallam University
Sheffield, South Yorkshire, UK

Additional material to this book can be downloaded from http://extras.springer.com.
ISBN 978-1-4471-5253-8
ISBN 978-1-4471-5254-5 (eBook)
DOI 10.1007/978-1-4471-5254-5
Springer London Heidelberg New York Dordrecht
Library of Congress Control Number: 2013946037
1st edition: © Addison-Wesley 2003
© Springer-Verlag London 2006, 2013
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Exempted from this legal reservation are brief excerpts in connection with reviews or scholarly analysis or material supplied specifically for the purpose of being entered and executed on a computer system, for exclusive use by the purchaser of the work. Duplication of this publication or parts thereof is permitted only under the provisions of the Copyright Law of the Publisher’s location, in its current version, and permission for use must always be obtained from Springer.
Permissions for use may be obtained through RightsLink at the Copyright Clearance Center. Violations are liable to prosecution under the respective Copyright Law.
The use of general descriptive names, registered names, trademarks, service marks, etc. in this publication does not imply, even in the absence of a specific statement, that such names are exempt from the relevant protective laws and regulations and therefore free for general use.
While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein.
Printed on acid-free paper

Springer is part of Springer Science+Business Media (www.springer.com)

Preface to Third Edition

It is now 7 years since I wrote the second edition of An Introduction to Network
Programming with Java and so, when approached to produce a third edition, I felt that it was an appropriate time to agree to do so (possibly rather later than it should have been). One of the very first things that I did after being approached was examined the literature to find out what texts had been produced in the
Java/network programming area in the interim period, and so what the current state of the competition was. (Though I had had a strong interest in this area for a considerable number of years, I had also been involved in other areas of software development, of course, and hadn’t had cause to examine the literature in this area for some time.) To my great surprise, I found that virtually nothing of any consequence had been produced in this area during those years! Of course, this was a very welcome surprise and provided further impetus to go ahead with the project.
The changes in this third edition are not as profound as those in the second edition, largely because Java 5 brought in major language changes (both network and non-network) that needed to be reflected in the second edition, whereas neither
Java 6 nor Java 7 has had such an impact, particularly in the area of network programming. One major change that did occur during this time, and is worth mentioning, was Sun’s takeover by Oracle in April of 2009, but this has had no significant effect on the way in which Java has been developed.
Since the changes that have been necessary since the second edition are somewhat more small-scale than those that were desirable after the first edition,
I think that it would be useful to give a chapter-by-chapter indication of what has been changed, what has been introduced that wasn’t there before and, in some cases, what has been removed completely (the last of these hopefully resulting in a more ‘streamlined’ product). Consequently, the great bulk of the remainder of this preface will comprise a chapter-by-chapter breakdown of those changes.

v

vi

Preface to Third Edition

Chapter 1
• Updating of browsers and browser versions used (along with associated updating of screenshots).
• Updating of the comparison between TCP and UDP.
Chapter 2
• Removal of Sect. 2.4 (‘Downloading Web Pages’), felt by me to be of little use to most people.
• Some very minor changes to lines of code.
Chapter 3
• Extra text devoted to the differing strategies for determining which thread from a group of competing threads is to be given use of the processor at any given time.
Chapter 4
• Addition of ArrayLists and associated relegation of Vectors (with consequent modification of example program).
• Comparison of Vectors and ArrayLists.
Chapter 5
• Removal of step 2 in 5.3 (compiling with rmic), which has actually been unnecessary since Java 5.
• Vector references replaced with ArrayList ones in bank example of 5.4.
Chapter 6
• Some very minor URL changes.
Chapter 7
• Statement of redundancy of the loading of the database driver (for all JDBC4compatible drivers), with consequent removal from examples. (JDBC4 was part of Java 6, which was introduced in December of 2006.)
• Addition of material on Apache Derby/Java DB, which came in with Java 6. This material introduced in a new Sect. 7.6, with consequent re-numbering of the old
7.6 and all later sections in this chapter.
• Information about Jakarta’s retirement on 21/12/11 (and consequent direct control of Jakarta’s sub-projects by Apache).
• Changes to the steps required in the new Sect. 7.12 (previously 7.11) for using the DataSource interface and creating a DAO (this method having changed somewhat since 2006), with consequent changes to the code of the example. • Modification of the steps required for downloading and extracting DBCP files.

Preface to Third Edition

vii

Chapter 8
• Updating of the Servlet API installation instructions.
• Removal of references to Tomcat’s ROOT folder (now no longer in existence).
• Introduction of servlet annotation lines (introduced in Java 6).
Chapter 9
• Replacement of some HTML code with HTML-5 compatible CSS.
• Some very minor changes to lines of code.
Chapter 10
• Removal of Sect. 10.1, due to the Bean Builder now being defunct and no replacement for this software having appeared.
• Removal of the requirement that beans implement the Serializable interface, since this is (now?) unnecessary, with associated removal of the clause implements Serializable from the examples.
• Introduction of CSS into examples, to make examples HTML-5 compatible.
(Old) Chapter 11
• Removal of this entire chapter (with consequent re-numbering of later chapters).
This has been done partly because EJPs are no longer of such importance since the emergence of frameworks such as Hibernate and Spring and partly because I felt that the complexity of EJBs probably didn’t warrant their inclusion in this text.
New ‘Chapter 11’ (Previously ‘Chapter 12’)
• Very minor changes of wording.
New ‘Chapter 12’ (Previously ‘Chapter 13’)
• Updating of browsers used.
In keeping with the society-wide move towards Internet storage, there is now no
CD accompanying this text. Model solutions for end-of-chapter exercises are accessible by lecturers and other authorised individuals through access/application form via http://springer.com/978-1-4471-5253-8. Also included at this URL is a Word document called Java Environment Installation that provides downloading and installation instructions for Java 7 and all associated software required to complete the end-of-chapter exercises. (The instructions will not refer to the latest update of
Java 7, so please download whatever is the latest update.)
At a second URL (http://extras.springer.com) are the items listed below, which can be found by searching for the book’s ISBN (978-1-4471-5253-8).
• Chapter examples
• Supplied code
• GIF files

viii

Preface to Third Edition

• JPEG files
• Sound files
• Videos
All that remains now is for me to wish you luck and satisfaction in your programming endeavours. Good luck!
Sheffield, South Yorkshire, UK
27 March 2013

Jan Graba

Contents

1

Basic Concepts, Protocols and Terminology .........................................
1.1 Clients, Servers and Peers ................................................................
1.2 Ports and Sockets .............................................................................
1.3 The Internet and IP Addresses .........................................................
1.4 Internet Services, URLs and DNS ...................................................
1.5 TCP ..................................................................................................
1.6 UDP..................................................................................................

1
1
2
3
4
5
7

2

Starting Network Programming in Java...............................................
2.1 The InetAddress Class ......................................................................
2.2 Using Sockets...................................................................................
2.2.1 TCP Sockets .........................................................................
2.2.2 Datagram (UDP) Sockets .....................................................
2.3 Network Programming with GUIs ...................................................

9
9
12
12
20
28

3

Multithreading and Multiplexing ..........................................................
3.1 Thread Basics ...................................................................................
3.2 Using Threads in Java ......................................................................
3.2.1 Extending the Thread Class .................................................
3.2.2 Explicitly Implementing the Runnable Interface .................
3.3 Multithreaded Servers ......................................................................
3.4 Locks and Deadlock .........................................................................
3.5 Synchronising Threads.....................................................................
3.6 Non-blocking Servers ......................................................................
3.6.1 Overview ..............................................................................
3.6.2 Implementation ....................................................................
3.6.3 Further Details......................................................................

47
48
49
49
54
56
61
63
71
71
72
81

4

File Handling ...........................................................................................
4.1 Serial Access Files ...........................................................................
4.2 File Methods ....................................................................................
4.3 Redirection .......................................................................................

87
87
93
96
ix

x

Contents

4.4 Command Line Parameters ............................................................
4.5 Random Access Files .....................................................................
4.6 Serialisation [U.S. Spelling Serialization] .....................................
4.7 File I/O with GUIs .........................................................................
4.8 ArrayLists.......................................................................................
4.9 ArrayLists and Serialisation ...........................................................
4.10 Vectors Versus ArrayLists ..............................................................

96
98
105
109
115
117
124

5

Remote Method Invocation (RMI) ........................................................
5.1 The Basic RMI Process ..................................................................
5.2 Implementation Details ..................................................................
5.3 Compilation and Execution............................................................
5.4 Using RMI Meaningfully...............................................................
5.5 RMI Security..................................................................................

129
129
130
134
136
145

6

CORBA ....................................................................................................
6.1 Background and Basics ..................................................................
6.2 The Structure of a Java IDL Specification .....................................
6.3 The Java IDL Process ....................................................................
6.4 Using Factory Objects....................................................................
6.5 Object Persistence ..........................................................................
6.6 RMI-IIOP .......................................................................................

151
151
152
156
165
175
176

7

Java Database Connectivity (JDBC) .....................................................
7.1 The Vendor Variation Problem .......................................................
7.2 SQL and Versions of JDBC............................................................
7.3 Creating an ODBC Data Source ....................................................
7.4 Simple Database Access ................................................................
7.5 Modifying the Database Contents..................................................
7.6 Java DB/Apache Derby ..................................................................
7.7 Transactions ...................................................................................
7.8 Meta Data .......................................................................................
7.9 Using a GUI to Access a Database ................................................
7.10 Scrollable ResultSets ......................................................................
7.11 Modifying Databases via Java Methods ........................................
7.12 Using the DataSource Interface .....................................................
7.12.1 Overview and Support Software ......................................
7.12.2 Defining a JNDI Resource Reference ..............................
7.12.3 Mapping the Resource Reference onto a Real Resource .....
7.12.4 Obtaining the Data Source Connection ...........................
7.12.5 Data Access Objects ........................................................

179
180
180
182
182
189
193
195
196
200
203
207
212
212
214
215
216
217

8

Servlets .....................................................................................................
8.1 Servlet Basics .................................................................................
8.2 Setting Up the Servlet API .............................................................
8.3 Creating a Web Application ...........................................................

225
226
226
228

Contents

xi

8.4 The Servlet URL and the Invoking Web Page ...............................
8.5 Servlet Structure.............................................................................
8.6 Testing a Servlet .............................................................................
8.7 Passing Data ...................................................................................
8.8 Sessions ..........................................................................................
8.9 Cookies ..........................................................................................
8.10 Accessing a Database via a Servlet ................................................

230
231
233
233
240
252
260

9

JavaServer Pages (JSPs) .........................................................................
9.1 The Rationale Behind JSPs ............................................................
9.2 Compilation and Execution............................................................
9.3 JSP Tags .........................................................................................
9.3.1 Directives .........................................................................
9.3.2 Declarations......................................................................
9.3.3 Expressions ......................................................................
9.3.4 Scriptlets...........................................................................
9.3.5 Comments ........................................................................
9.3.6 Actions..............................................................................
9.4 Implicit JSP Objects .....................................................................
9.5 Collaborating with Servlets............................................................
9.6 JSPs in Action ................................................................................
9.7 Error Pages .....................................................................................
9.8 Using JSPs to Access Remote Databases.......................................

269
269
270
271
272
272
272
273
274
274
274
276
276
281
284

10

JavaBeans.................................................................................................
10.1 Creating a JavaBean .......................................................................
10.2 Exposing a Bean’s Properties.........................................................
10.3 Making Beans Respond to Events .................................................
10.4 Using JavaBeans Within an Application ........................................
10.5 Bound Properties............................................................................
10.6 Using JavaBeans in JSPs................................................................
10.6.1 The Basic Procedure ........................................................
10.6.2 Calling a Bean’s Methods Directly ..................................
10.6.3 Using HTML Tags to Manipulate a Bean’s Properties ....

287
288
293
296
297
300
306
306
308
312

11

Multimedia...............................................................................................
11.1 Transferring and Displaying Images Easily ...................................
11.2 Transferring Media Files ................................................................
11.3 Playing Sound Files .......................................................................
11.4 The Java Media Framework ...........................................................

327
328
332
338
340

12

Applets......................................................................................................
12.1 Applets and JApplets ......................................................................
12.2 Applet Basics and the Development Process .................................
12.3 The Internal Operation of Applets .................................................
12.4 Using Images in Applets ................................................................

347
348
348
350
354

xii

Contents

12.4.1 Using Class Image............................................................
12.4.2 Using Class ImageIcon ....................................................
12.5 Scaling Images ...............................................................................
12.6 Using Sound in Applets .................................................................

355
360
362
363

Appendix: Structured Query Language (SQL)............................................
A.1 DDL Statements ............................................................................
A.1.1 Creating a Table ...............................................................
A.1.2 Deleting a Table ...............................................................
A.1.3 Adding Attributes .............................................................
A.1.4 Removing Attributes ........................................................
A.2 DML Statements ............................................................................
A.2.1 SELECT ...........................................................................
A.2.2 INSERT ............................................................................
A.2.3 DELETE...........................................................................
A.2.4 UPDATE ..........................................................................

369
370
370
370
371
371
371
372
373
373
373

Index ................................................................................................................. 375

Chapter 1

Basic Concepts, Protocols and Terminology

Learning Objectives
After reading this chapter, you should:
• have a high level appreciation of the basic means by which messages are sent and received on modern networks;
• be familiar with the most important protocols used on networks;
• understand the addressing mechanism used on the Internet;
• understand the basic principles of client/server programming.
The fundamental purpose of this opening chapter is to introduce the underpinning network principles and associated terminology with which the reader will need to be familiar in order to make sense of the later chapters of this book. The material covered here is entirely generic (as far as any programming language is concerned) and it is not until the next chapter that we shall begin to consider how Java may be used in network programming. If the meaning of any term covered here is not clear when that term is later encountered in context, the reader should refer back to this chapter to refresh his/her memory.
It would be very easy to make this chapter considerably larger than it currently is, simply by including a great deal of dry, technical material that would be unlikely to be of any practical use to the intended readers of this book. However, this chapter is intentionally brief, the author having avoided the inclusion of material that is not of relevance to the use of Java for network programming. The reader who already has a sound grasp of network concepts may safely skip this chapter entirely.

1.1

Clients, Servers and Peers

The most common categories of network software nowadays are clients and servers.
These two categories have a symbiotic relationship and the term client/server programming has become very widely used in recent years. It is important to
J. Graba, An Introduction to Network Programming with Java: Java 7 Compatible,
DOI 10.1007/978-1-4471-5254-5_1, © Springer-Verlag London 2013

1

2

1

Basic Concepts, Protocols and Terminology

distinguish firstly between a server and the machine upon which the server is running
(called the host machine), since I.T. workers often refer loosely to the host machine as ‘the server’. Though this common usage has no detrimental practical effects for the majority of I.T. tasks, those I.T. personnel who are unaware of the distinction and subsequently undertake network programming are likely to be caused a significant amount of conceptual confusion until this distinction is made known to them.
A server, as the name implies, provides a service of some kind. This service is provided for clients that connect to the server’s host machine specifically for the purpose of accessing the service. Thus, it is the clients that initiate a dialogue with the server. (These clients, of course, are also programs and are not human clients!)
Common services provided by such servers include the ‘serving up’ of Web pages
(by Web servers) and the downloading of files from servers’ host machines via the
File Transfer Protocol (FTP servers). For the former service, the corresponding client programs would be Web browsers (such as Firefox, Chrome or Internet
Explorer). Though a client and its corresponding server will normally run on different machines in a real-world application, it is perfectly possible for such programs to run on the same machine. Indeed, it is often very convenient (as will be seen in subsequent chapters) for server and client(s) to be run on the same machine, since this provides a very convenient ‘sandbox’ within which such applications may be tested before being released (or, more likely, before final testing on separate machines). This avoids the need for multiple machines and multiple testing personnel. In some applications, such as messaging services, it is possible for programs on users’ machines to communicate directly with each other in what is called peer-topeer (or P2P) mode. However, for many applications, this is either not possible or prohibitively costly in terms of the number of simultaneous connections required.
For example, the World Wide Web simply does not allow clients to communicate directly with each other. However, some applications use a server as an intermediary, in order to provide ‘simulated’peer-to-peer facilities. Alternatively, both ends of the dialogue may act as both client and server. Peer-to-peer systems are beyond the intended scope of this text, though, and no further mention will be made of them.

1.2

Ports and Sockets

These entities lie at the heart of network communications. For anybody not already familiar with the use of these terms in a network programming context, the two words very probably conjure up images of hardware components. However, although they are closely associated with the hardware communication links between computers within a network, ports and sockets are not themselves hardware elements, but abstract concepts that allow the programmer to make use of those communication links.
A port is a logical connection to a computer (as opposed to a physical connection) and is identified by a number in the range 1–65535. This number has no

1.3

The Internet and IP Addresses

3

correspondence with the number of physical connections to the computer, of which there may be only one (even though the number of ports used on that machine may be much greater than this). Ports are implemented upon all computers attached to a network, but it is only those machines that have server programs running on them for which the network programmer will refer explicitly to port numbers. Each port may be dedicated to a particular server/service (though the number of available ports will normally greatly exceed the number that is actually used). Port numbers in the range 1–1023 are normally set aside for the use of specified standard services, often referred to as ‘well-known’ services. For example, port 80 is normally used by
Web servers. Some of the more common well-known services are listed in Sect. 1.4.
Application programs wishing to use ports for non-standard services should avoid using port numbers 1–1023. (A range of 1024–65535 should be more than enough for even the most prolific of network programmers!).
For each port supplying a service, there is a server program waiting for any requests. All such programs run together in parallel on the host machine. When a client attempts to make connection with a particular server program, it supplies the port number of the associated service. The host machine examines the port number and passes the client’s transmission to the appropriate server program for processing. In most applications, of course, there are likely to be multiple clients wanting the same service at the same time. A common example of this requirement is that of multiple browsers (quite possibly thousands of them) wanting Web pages from the same server. The server, of course, needs some way of distinguishing between clients and keeping their dialogues separate from each other. This is achieved via the use of sockets. As stated earlier, a socket is an abstract concept and not an element of computer hardware. It is used to indicate one of the two end-points of a communication link between two processes. When a client wishes to make connection to a server, it will create a socket at its end of the communication link. Upon receiving the client’s initial request (on a particular port number), the server will create a new socket at its end that will be dedicated to communication with that particular client. Just as one hardware link to a server may be associated with many ports, so too may one port be associated with many sockets. More will be said about sockets in Chap. 2.

1.3

The Internet and IP Addresses

An internet (lower-case ‘i’) is a collection of computer networks that allows any computer on any of the associated networks to communicate with any other computer located on any of the other associated networks (or on the same network, of course). The protocol used for such communication is called the Internet
Protocol (IP). The Internet (upper-case ‘I’) is the world’s largest IP-based network. Each computer on the Internet has a unique IP address, the current version of which is still, for most people, IPv4 (Internet Protocol version 4), though this is likely to change at some point during the next few years. This represents

1

4

Basic Concepts, Protocols and Terminology

machine addresses in what is called quad notation. This is made up of four eight-bit numbers (i.e., numbers in the decimal range 0–255), separated by dots.
For example, 131.122.3.219 would be one such address. Due to a growing shortage of IPv4 addresses, IPv4 is due to be replaced with IPv6, the draft standard for which was published on the 10th of August, 1998. IPv6 uses 128-bit addresses, which provide massively more addresses. Many common Internet applications already work with IPv6 and it is expected that IPv6 will gradually replace IPv4, with the two coexisting for a number of years during a transition period.
Recent years have witnessed an explosion in the growth and use of the Internet.
As a result, there has arisen a need for a programming language with features designed specifically for network programming. Java provides these features and does so in a platform-independent manner, which is vital for a heterogeneous network such as the Internet. Java is sometimes referred to as ‘the language of the
Internet’ and it is the use of Java in this context that has had a major influence on the popularisation of the language. For many programmers, the need to program for the Internet is one of the main reasons, if not the reason, for learning to program in Java.

1.4

Internet Services, URLs and DNS

Whatever the service provided by a server, there must be some established protocol governing the communication that takes place between server and client. Each end of the dialogue must know what may/must be sent to the other, the format in which it should be sent, the sequence in which it must be sent (if sequence matters) and, for ‘open-ended’ dialogues, how the dialogue is to be terminated. For the standard services, such protocols are made available in public documents, usually by either the Internet Engineering Task Force (IETF) or the World Wide Web
Consortium (W3C). Some of the more common services and their associated ports are shown in Table 1.1. For a more esoteric or ‘bespoke’ service, the application writer must establish a protocol and convey it to the intended users of that service.
Table 1.1 Some well-known network services
Protocol name
Echo

Port number
7

Daytime

13

FTP-data
FTP
Telnet
SMTP
HTTP
NNTP

20
21
23
25
80
119

Nature of service
The server simply echoes the data sent to it. This is useful for testing purposes
Provides the ASCII representation of the current date and time on the server
Transferring files. (FTP uses two ports.)
Sending FTP commands like PUT and GET
Remote login and command line interaction
E-mail. (Simple Mail Transfer Protocol.)
HyperText Transfer Protocol (the World Wide Web protocol)
Usenet. (Network News Transfer Protocol.)

1.5

TCP

5

A URL (Uniform Resource Locator) is a unique identifier for any resource located on the Internet. It has the following structure (in which BNF notation is used):
://[:][/]
[/[#]]
For example: http://www.oracle.com/technetwork/java/javase/downloads/index.html For a well-known protocol, the port number may be omitted and the default port number will be assumed. Thus, since the example above specifies the HTTP protocol (the protocol of the Web) and does not specify on which port of the host machine the service is available, it will be assumed that the service is running on port 80 (the default port for Web servers). If the file name is omitted, then the server sends a default file from the directory specified in the path name. (This default file will commonly be called index.html or default.html.) The ‘section’ part of the URL (not often specified) indicates a named ‘anchor’ in an HTML document. For example, the
HTML anchor in the tag
Summary of Report would be referred to as summary by the section component of the URL.
Since human beings are generally much better at remembering meaningful strings of characters than they are at remembering long strings of numbers, the
Domain Name System was developed. A domain name, also known as a host name, is the user-friendly equivalent of an IP address. In the previous example of a URL, the domain name was www.oracle.com. The individual parts of a domain name don’t correspond to the individual parts of an IP address. In fact, domain names don’t always have four parts (as IPv4 addresses must have).
Normally, human beings will use domain names in preference to IP addresses, but they can just as well use the corresponding IP addresses (if they know what they are!). The Domain Name System provides a mapping between IP addresses and domain names and is held in a distributed database. The IP address system and the
DNS are governed by ICANN (the Internet Corporation for Assigned Names and
Numbers), which is a non-profitmaking organisation. When a URL is submitted to a browser, the DNS automatically converts the domain name part into its numeric IP equivalent. 1.5

TCP

In common with all modern computer networks, the Internet is a packet-switched network, which means that messages between computers on the Internet are broken up into blocks of information called packets, with each packet being handled separately and possibly travelling by a completely different route from that of other such

1

6

Basic Concepts, Protocols and Terminology

packets from the same message. IP is concerned with the routing of these packets through an internet. Introduced by the American military during the Cold War, it was designed from the outset to be robust. In the event of a military strike against one of the network routers, the rest of the network had to continue to function as normal, with messages that would have gone through the damaged router being rerouted. IP is responsible for this re-routing. It attaches the IP address of the intended recipient to each packet and then tries to determine the most efficient route available to get to the ultimate destination (taking damaged routers into account).
However, since packets could still arrive out of sequence, be corrupted or even not arrive at all (without indication to either sender or intended recipient that anything had gone wrong), it was decided to place another protocol layer on top of IP. This further layer was provided by TCP (Transmission Control Protocol), which allowed each end of a connection to acknowledge receipt of IP packets and/or request retransmission of lost or corrupted packets. In addition, TCP allows the packets to be rearranged into their correct sequence at the receiving end. IP and TCP are the two commonest protocols used on the Internet and are almost invariably coupled together as TCP/IP. TCP is the higher level protocol that uses the lower level IP.
For Internet applications, a four-layer model is often used, which is represented diagrammatically in Fig. 1.1 below. The transport layer will often comprise the TCP protocol, but may be UDP (described in the next section), while the internet layer will always be IP. Each layer of the model represents a different level of abstraction, with higher levels representing higher abstraction. Thus, although applications may appear to be communicating directly with each other, they are actually communicating directly only with their transport layers. The transport and internet layers, in their turn, communicate directly only with the layers immediately above and below them, while the host-to-network layer communicates directly only with the IP layer at each end of the connection. When a message is sent by the application layer at one end of the connection, it passes through each of the lower layers. As it does so, each layer adds further protocol data specific to the particular protocol at that level.
For the TCP layer, this process involves breaking up the data packets into TCP segments and adding sequence numbers and checksums; for the IP layer, it involves placing the TCP segments into IP packets called datagrams and adding the routing details. The host-to-network layer then converts the digital data into an analogue form suitable for transmission over the carrier wire, sends the data and converts it back into digital form at the receiving end.
Logical
Application Layer

path

Application Layer

Transport Layer (E.g., TCP)
Internet Layer (IP)

Fig. 1.1 The 4-layer network model Transport Layer (E.g., TCP)
Internet Layer (IP)

Host-to-network layer

1.6

UDP

7

At the receiving end, the message travels up through the layers until it reaches the receiving application layer. As it does so, each layer converts the message into a form suitable for receipt by the next layer (effectively reversing the corresponding process carried out at the sending end) and carries out checks appropriate to its own protocol. If recalculation of checksums reveals that some of the data has been corrupted or checking of sequence numbers shows that some data has not been received, then the transport layer requests re-transmission of the corrupt/missing data.
Otherwise, the transport layer acknowledges receipt of the packets. All of this is completely transparent to the application layer. Once all the data has been received, converted and correctly sequenced, it is presented to the recipient application layer as though that layer had been in direct communication with the sending application layer. The latter may then send a response in exactly the same manner (and so on).
In fact, since TCP provides full duplex transmission, the two ends of the connection may be sending data simultaneously.
The above description has deliberately hidden many of the low-level details of implementation, particularly the tasks carried out by the host-to-network layer.
In addition, of course, the initial transmission may have passed through several routers and their associated layers before arriving at its ultimate destination.
However, this high-level view covers the basic stages that are involved and is quite sufficient for our purposes.
Another network model that is often referred to is the seven-layer Open Systems
Interconnection (OSI) model. However, this model is an unnecessarily complex one for our purposes and is better suited to non-TCP/IP networks anyway.

1.6

UDP

Most Internet applications use TCP as their transport mechanism. In contrast to
TCP, User Datagram Protocol (UDP) is an unreliable protocol, since:
(i) it doesn’t guarantee that each packet of data will arrive;
(ii) it doesn’t guarantee that packets will be in the right order.
UDP doesn’t re-send a packet if it fails to arrive or there is some other error and it doesn’t re-assemble packets into the correct sequence at the receiving end. However, the TCP overhead of providing facilities such as confirmation of receipt and re-transmission of lost or corrupted packets used to mean that UDP was significantly faster than TCP. For many applications (e.g., file transfer), this didn’t really matter greatly. As far as these applications were concerned, it was much more important that the data arrived intact and in the correct sequence, both of which were guaranteed by TCP. For some applications, however, the relatively slow throughput speed offered by TCP was simply not feasible. Such applications included the streaming of audio and video files (i.e., the playing of those files while they were being downloaded). Such applications didn’t use TCP, because of its large overhead. Instead, they used UDP, since their major objective was to keep playing

8

1

Basic Concepts, Protocols and Terminology

the sound/video without interruption and losing a few bytes of data was much better than waiting for re-transmission of the missing data.
Nowadays, network transmission speeds are considerably greater than they were only a few years ago, meaning that UDP is now a feasible transport mechanism for applications in which it would not once have been considered. In addition to this, it is much easier for TCP packets to get through firewalls than it is for UDP packets to do so, since Web administrators tend to allow TCP packets from remote port 80s to pass through unchallenged. For these reasons, the choice of whether to use TCP or
UDP for speed-critical applications is not nearly as clear cut as it used to be.

Chapter 2

Starting Network Programming in Java

Learning Objectives
After reading this chapter, you should:





know how to determine the host machine’s IP address via a Java program; know how to use TCP sockets in both client programs and server programs; know how to use UDP sockets in both client programs and server programs; appreciate the convenience of Java’s stream classes and the consistency of the interface afforded by them;
• appreciate the ease with which GUIs can be added to network programs;
• know how to check whether ports on a specified machine are running services.
Having covered fundamental network protocols and techniques in a generic fashion in Chap. 1, it is now time to consider how those protocols may be used and the techniques implemented in Java. Core package java.net contains a number of very useful classes that allow programmers to carry out network programming very easily. Package javax.net, introduced in J2SE 1.4, contains factory classes for creating sockets in an implementation-independent fashion. Using classes from these packages
(primarily from the former), the network programmer can communicate with any server on the Internet or implement his/her own Internet server.

2.1

The InetAddress Class

One of the classes within package java.net is called InetAddress, which handles
Internet addresses both as host names and as IP addresses. Static method getByName of this class uses DNS (Domain Name System) to return the Internet address of a specified host name as an InetAddress object. In order to display the IP address from this object, we can simply use method println (which will cause the object’s toString method to be executed). Since method getByName throws the checked exception

J. Graba, An Introduction to Network Programming with Java: Java 7 Compatible,
DOI 10.1007/978-1-4471-5254-5_2, © Springer-Verlag London 2013

9

10

2 Starting Network Programming in Java

UnknownHostException if the host name is not recognised, we must either throw this exception or (preferably) handle it with a catch clause. The following example illustrates this.
Example
import java.net.*; import java.util.*; public class IPFinder
{
public static void main(String[] args)
{
String host;
Scanner input = new Scanner(System.in);
InetAddress address;
System.out.print("\n\nEnter host name: "); host = input.next(); try { address = InetAddress.getByName(host);
System.out.println("IP address: "
+ address.toString());
}
catch (UnknownHostException uhEx)
{
System.out.println("Could not find " + host);
}
}
}
The output from a test run of this program is shown in Fig. 2.1.

2.1

The InetAddress Class

11

Fig. 2.1 Using method getByName to retrieve IP address of a specified host

It is sometimes useful for Java programs to be able to retrieve the IP address of the current machine. The example below shows how to do this.
Example
import java.net.*; public class MyLocalIPAddress
{
public static void main(String[] args)
{
try
{
InetAddress address =
InetAddress.getLocalHost();
System.out.println(address);
}
catch (UnknownHostException uhEx)
{
System.out.println(
"Could not find local address!");
}
}
}
Output from this program when run on the author’s office machine is shown in
Fig. 2.2.

12

2 Starting Network Programming in Java

Fig. 2.2 Retrieving the current machine’s IP address

2.2

Using Sockets

As described in Chap. 1, different processes (programs) can communicate with each other across networks by means of sockets. Java implements both TCP/IP sockets and datagram sockets (UDP sockets). Very often, the two communicating processes will have a client/server relationship. The steps required to create client/ server programs via each of these methods are very similar and are outlined in the following two sub-sections.

2.2.1

TCP Sockets

A communication link created via TCP/IP sockets is a connection-orientated link.
This means that the connection between server and client remains open throughout the duration of the dialogue between the two and is only broken (under normal circumstances) when one end of the dialogue formally terminates the exchanges (via an agreed protocol). Since there are two separate types of process involved (client and server), we shall examine them separately, taking the server first. Setting up a server process requires five steps…
1. Create a ServerSocket object.
The ServerSocket constructor requires a port number (1024–65535, for non-reserved ones) as an argument. For example:
ServerSocket serverSocket = new ServerSocket(1234);

2.2

Using Sockets

13

In this example, the server will await (‘listen for’) a connection from a client on port 1234.
2. Put the server into a waiting state.
The server waits indefinitely (‘blocks’) for a client to connect. It does this by calling method accept of class ServerSocket, which returns a Socket object when a connection is made. For example:
Socket link = serverSocket.accept();
3. Set up input and output streams.
Methods getInputStream and getOutputStream of class Socket are used to get references to streams associated with the socket returned in step 2. These streams will be used for communication with the client that has just made connection. For a non-GUI application, we can wrap a Scanner object around the InputStream object returned by method getInputStream, in order to obtain string-orientated input (just as we would do with input from the standard input stream, System.in).
For example:
Scanner input = new Scanner(link.getInputStream());
Similarly, we can wrap a PrintWriter object around the OutputStream object returned by method getOutputStream. Supplying the PrintWriter constructor with a second argument of true will cause the output buffer to be flushed for every call of println (which is usually desirable). For example:
PrintWriter output = new PrintWriter(link.getOutputStream(),true);
4. Send and receive data.
Having set up our Scanner and PrintWriter objects, sending and receiving data is very straightforward. We simply use method nextLine for receiving data and method println for sending data, just as we might do for console I/O. For example: output.println("Awaiting data…");
String input = input.nextLine();
5. Close the connection (after completion of the dialogue).
This is achieved via method close of class Socket. For example: link.close(); The following example program is used to illustrate the use of these steps.
Example
In this simple example, the server will accept messages from the client and will keep count of those messages, echoing back each (numbered) message. The main protocol for this service is that client and server must alternate between sending and receiving (with the client initiating the process with its opening message, of course).
The only details that remain to be determined are the means of indicating when the

14

2 Starting Network Programming in Java

dialogue is to cease and what final data (if any) should be sent by the server. For this simple example, the string “***CLOSE***” will be sent by the client when it wishes to close down the connection. When the server receives this message, it will confirm the number of preceding messages received and then close its connection to this client. The client, of course, must wait for the final message from the server before closing the connection at its own end.
Since an IOException may be generated by any of the socket operations, one or more try blocks must be used. Rather than have one large try block (with no variation in the error message produced and, consequently, no indication of precisely what operation caused the problem), it is probably good practice to have the opening of the port and the dialogue with the client in separate try blocks. It is also good practice to place the closing of the socket in a finally clause, so that, whether an exception occurs or not, the socket will be closed (unless, of course, the exception is generated when actually closing the socket, but there is nothing we can do about that).
Since the finally clause will need to know about the Socket object, we shall have to declare this object within a scope that covers both the try block handling the dialogue and the finally block. Thus, step 2 shown above will be broken up into separate declaration and assignment. In our example program, this will also mean that the Socket object will have to be explicitly initialised to null (as it will not be a global variable).
Since a server offering a public service would keep running indefinitely, the call to method handleClient in our example has been placed inside an ‘infinite’ loop, thus: do { handleClient(); }while (true);
In the code that follows (and in later examples), port 1234 has been chosen for the service, but it could just as well have been any integer in the range 1024–65535.
Note that the lines of code corresponding to each of the above steps have been clearly marked with emboldened comments.
//Server that echoes back client's messages.
//At end of dialogue, sends message indicating
//number of messages received. Uses TCP. import java.io.*; import java.net.*; import java.util.*; public class TCPEchoServer
{
private static ServerSocket serverSocket; private static final int PORT = 1234; public static void main(String[] args)

2.2

Using Sockets

15

{
System.out.println("Opening port…\n"); try { serverSocket = new ServerSocket(PORT);//Step 1.
}
catch(IOException ioEx)
{
System.out.println(
"Unable to attach to port!");
System.exit(1);
} do { handleClient(); }while (true);
}
private static void handleClient()
{
Socket link = null;

//Step 2.

try
{
link = serverSocket.accept();

//Step 2.

Scanner input = new Scanner(link.getInputStream());//Step 3.
PrintWriter output = new PrintWriter( link.getOutputStream(),true); //Step 3. int numMessages = 0;
String message = input.nextLine();
//Step 4. while (!message.equals("***CLOSE***"))
{
System.out.println("Message received."); numMessages++; output.println("Message " + numMessages
+ ": " + message); //Step 4. message = input.nextLine();
}
output.println(numMessages
+ " messages received.");//Step 4.
}

16

2 Starting Network Programming in Java

catch(IOException ioEx)
{
ioEx.printStackTrace();
}
finally
{
try
{
System.out.println(
"\n* Closing connection… *"); link.close(); //Step 5.
}
catch(IOException ioEx)
{
System.out.println(
"Unable to disconnect!");
System.exit(1);
}
}
}
}
Setting up the corresponding client involves four steps…
1. Establish a connection to the server.
We create a Socket object, supplying its constructor with the following two arguments: • the server’s IP address (of type InetAddress);
• the appropriate port number for the service.
(The port number for server and client programs must be the same, of course!)
For simplicity’s sake, we shall place client and server on the same host, which will allow us to retrieve the IP address by calling static method getLocalHost of class InetAddress. For example:
Socket link = new Socket(InetAddress.getLocalHost(),1234);
2. Set up input and output streams.
These are set up in exactly the same way as the server streams were set up (by calling methods getInputStream and getOutputStream of the Socket object that was created in step 2).
3. Send and receive data.
The Scanner object at the client end will receive messages sent by the PrintWriter object at the server end, while the PrintWriter object at the client end will send messages that are received by the Scanner object at the server end (using methods nextLine and println respectively).

2.2

Using Sockets

17

4. Close the connection.
This is exactly the same as for the server process (using method close of class
Socket).
The code below shows the client program for our example. In addition to an input stream to accept messages from the server, our client program will need to set up an input stream (as another Scanner object) to accept user messages from the keyboard. As for the server, the lines of code corresponding to each of the above steps have been clearly marked with emboldened comments. import java.io.*; import java.net.*; import java.util.*; public class TCPEchoClient
{
private static InetAddress host; private static final int PORT = 1234; public static void main(String[] args)
{
try
{
host = InetAddress.getLocalHost();
}
catch(UnknownHostException uhEx)
{
System.out.println("Host ID not found!");
System.exit(1);
} accessServer(); } private static void accessServer()
{
Socket link = null;
//Step 1. try { link = new Socket(host,PORT);

//Step 1.

Scanner input = new Scanner(link.getInputStream());
//Step 2.
PrintWriter output = new PrintWriter( link.getOutputStream(),true); //Step 2.
//Set up stream for keyboard entry…
Scanner userEntry = new Scanner(System.in);

18

2 Starting Network Programming in Java

String message, response; do {
System.out.print("Enter message: "); message = userEntry.nextLine(); output.println(message); //Step 3. response = input.nextLine(); //Step 3.
System.out.println("\nSERVER> "+response);
}while (!message.equals("***CLOSE***"));
}
catch(IOException ioEx)
{
ioEx.printStackTrace();
}
finally
{
try
{
System.out.println(
"\n* Closing connection… *"); link.close(); //Step 4.
}
catch(IOException ioEx)
{
System.out.println(
"Unable to disconnect!");
System.exit(1);
}
}
}
}
For the preceding client–server application to work, TCP/IP must be installed and working. How are you to know whether this is the case for your machine? Well, if there is a working Internet connection on your machine, then TCP/IP is running.
In order to start the application, first open two command windows and then start the server running in one window and the client in the other. (Make sure that the server is running first, in order to avoid having the client program crash!) The example screenshots in Figs. 2.3 and 2.4 show the dialogues between the server and two consecutive clients for this application. Note that, in order to stop the TCPEchoServer program, Ctrl-C has to be entered from the keyboard.

2.2

Using Sockets

Fig. 2.3 Example output from the TCPEchoServer program

Fig. 2.4 Example output from the TCPEchoClient program

19

20

2 Starting Network Programming in Java

2.2.2

Datagram (UDP) Sockets

Unlike TCP/IP sockets, datagram sockets are connectionless. That is to say, the connection between client and server is not maintained throughout the duration of the dialogue. Instead, each datagram packet is sent as an isolated transmission whenever necessary. As noted in Chap. 1, datagram (UDP) sockets provide a (usually) faster means of transmitting data than TCP/IP sockets, but they are unreliable.
Since the connection is not maintained between transmissions, the server does not create an individual Socket object for each client, as it did in our TCP/
IP example. A further difference from TCP/IP sockets is that, instead of a
ServerSocket object, the server creates a DatagramSocket object, as does each client when it wants to send datagram(s) to the server. The final and most significant difference is that DatagramPacket objects are created and sent at both ends, rather than simple strings.
Following the style of coverage for TCP client/server applications, the detailed steps required for client and server will be described separately, with the server process being covered first. This process involves the following nine steps, though only the first eight steps will be executed under normal circumstances…
1. Create a DatagramSocket object.
Just as for the creation of a ServerSocket object, this means supplying the object’s constructor with the port number. For example:
DatagramSocket datagramSocket = new DatagramSocket(1234);
2. Create a buffer for incoming datagrams.
This is achieved by creating an array of bytes. For example: byte[] buffer = new byte[256];
3. Create a DatagramPacket object for the incoming datagrams.
The constructor for this object requires two arguments:
• the previously-created byte array;
• the size of this array.
For example:
DatagramPacket inPacket = new DatagramPacket(buffer, buffer.length);
4. Accept an incoming datagram.
This is effected via the receive method of our DatagramSocket object, using our
DatagramPacket object as the receptacle. For example: datagramSocket.receive(inPacket); 2.2

Using Sockets

21

5. Accept the sender’s address and port from the packet.
Methods getAddress and getPort of our DatagramPacket object are used for this.
For example:
InetAddress clientAddress = inPacket.getAddress(); int clientPort = inPacket.getPort();
6. Retrieve the data from the buffer.
For convenience of handling, the data will be retrieved as a string, using an overloaded form of the String constructor that takes three arguments:
• a byte array;
• the start position within the array (= 0 here);
• the number of bytes (= full size of buffer here).
For example:
String message =

new String(inPacket.getData(),
0,inPacket.getLength());

7. Create the response datagram.
Create a DatagramPacket object, using an overloaded form of the constructor that takes four arguments:





the byte array containing the response message; the size of the response; the client’s address; the client’s port number.

The first of these arguments is returned by the getBytes method of the String class (acting on the desired String response). For example:
DatagramPacket outPacket = new DatagramPacket(response.getBytes(), response.length(),clientAddress, clientPort);
(Here, response is a String variable holding the return message.)
8. Send the response datagram.
This is achieved by calling method send of our DatagramSocket object, supplying our outgoing DatagramPacket object as an argument. For example: datagramSocket.send(outPacket); Steps 4–8 may be executed indefinitely (within a loop).
Under normal circumstances, the server would probably not be closed down at all. However, if an exception occurs, then the associated DatagramSocket should be closed, as shown in step 9 below.
9. Close the DatagramSocket.
This is effected simply by calling method close of our DatagramSocket object. For example: datagramSocket.close();

22

2 Starting Network Programming in Java

To illustrate the above procedure and to allow easy comparison with the equivalent
TCP/IP code, the example from Sect. 2.2.1 will be employed again. As before, the lines of code corresponding to each of the above steps are indicated via emboldened comments. Note that the numMessages part of the message that is returned by the server is somewhat artificial, since, in a real-world application, many clients could be making connection and the overall message numbers would not mean a great deal to individual clients. However, the cumulative message-numbering will serve to emphasise that there are no separate sockets for individual clients.
There are two other differences from the equivalent TCP/IP code that are worth noting, both concerning the possible exceptions that may be generated:
• the IOException in main is replaced with a SocketException;
• there is no checked exception generated by the close method in the finally clause, so there is no try block.
Now for the code…
//Server that echoes back client's messages.
//At end of dialogue, sends message indicating number of
//messages received. Uses datagrams. import java.io.*; import java.net.*; public class
{
private private private private UDPEchoServer static static static static

final int PORT = 1234;
DatagramSocket datagramSocket;
DatagramPacket inPacket, outPacket; byte[] buffer;

public static void main(String[] args)
{
System.out.println("Opening port…\n"); try { datagramSocket = new DatagramSocket(PORT);
//Step 1.
}
catch(SocketException sockEx)
{
System.out.println("Unable to open port!");
System.exit(1);
} handleClient(); }

2.2

Using Sockets

23

private static void handleClient()
{
try
{
String messageIn,messageOut; int numMessages = 0;
InetAddress clientAddress = null; int clientPort; do { buffer = new byte[256];
//Step 2. inPacket = new DatagramPacket( buffer, buffer.length);
//Step 3. datagramSocket.receive(inPacket); //Step 4. clientAddress = inPacket.getAddress();
//Step 5. clientPort = inPacket.getPort();
//Step 5. messageIn = new String(inPacket.getData(),
0,inPacket.getLength());
//Step 6.
System.out.println("Message received."); numMessages++; messageOut = "Message " + numMessages
+ ": " + messageIn; outPacket = new DatagramPacket(messageOut.getBytes(), messageOut.length(),clientAddress, clientPort);
//Step 7. datagramSocket.send(outPacket); //Step 8.
}while (true);
}
catch(IOException ioEx)
{
ioEx.printStackTrace();
}

24

2 Starting Network Programming in Java

finally

//If exception thrown, close connection. {
System.out.println(
"\n* Closing connection… *"); datagramSocket.close(); //Step 9.
}
}
}
Setting up the corresponding client requires the eight steps listed below.
1. Create a DatagramSocket object.
This is similar to the creation of a DatagramSocket object in the server program, but with the important difference that the constructor here requires no argument, since a default port (at the client end) will be used. For example:
DatagramSocket datagramSocket = new DatagramSocket();
2. Create the outgoing datagram.
This step is exactly as for step 7 of the server program. For example:
DatagramPacket outPacket = new DatagramPacket(message.getBytes(), message.length(), host, PORT);
3. Send the datagram message.
Just as for the server, this is achieved by calling method send of the DatagramSocket object, supplying our outgoing DatagramPacket object as an argument. For example: datagramSocket.send(outPacket); Steps 4–6 below are exactly the same as steps 2–4 of the server procedure.
4. Create a buffer for incoming datagrams.
For example: byte[] buffer = new byte[256];
5. Create a DatagramPacket object for the incoming datagrams.
For example:
DatagramPacket inPacket = new DatagramPacket(buffer, buffer.length);
6. Accept an incoming datagram.
For example: datagramSocket.receive(inPacket); 2.2

Using Sockets

25

7. Retrieve the data from the buffer.
This is the same as step 6 in the server program. For example:
String response = new String(inPacket.getData(),0, inPacket.getLength()); Steps 2–7 may then be repeated as many times as required.
8. Close the DatagramSocket.
This is the same as step 9 in the server program. For example: datagramSocket.close(); As was the case in the server code, there is no checked exception generated by the above close method in the finally clause of the client program, so there will be no try block. In addition, since there is no inter-message connection maintained between client and server, there is no protocol required for closing down the dialogue.
This means that we do not wish to send the final ‘***CLOSE***’ string (though we shall continue to accept this from the user, since we need to know when to stop sending messages at the client end). The line of code (singular, this time) corresponding to each of the above steps will be indicated via an emboldened comment.
Now for the code itself… import java.io.*; import java.net.*; import java.util.*; public class UDPEchoClient
{
private static InetAddress host; private static final int PORT = 1234; private static DatagramSocket datagramSocket; private static DatagramPacket inPacket, outPacket; private static byte[] buffer; public static void main(String[] args)
{
try
{
host = InetAddress.getLocalHost();
}
catch(UnknownHostException uhEx)
{
System.out.println("Host ID not found!");
System.exit(1);
}

26

2 Starting Network Programming in Java

accessServer();
}
private static void accessServer()
{
try
{
//Step 1… datagramSocket = new DatagramSocket();
//Set up stream for keyboard entry…
Scanner userEntry = new Scanner(System.in);
String message="", response=""; do {
System.out.print("Enter message: "); message = userEntry.nextLine(); if (!message.equals("***CLOSE***"))
{
outPacket = new DatagramPacket( message.getBytes(), message.length(), host,PORT); //Step 2.
//Step 3… datagramSocket.send(outPacket); buffer = new byte[256];
//Step 4. inPacket = new DatagramPacket( buffer, buffer.length);//Step 5.
//Step 6… datagramSocket.receive(inPacket); response = new String(inPacket.getData(),
0, inPacket.getLength());
//Step 7.
System.out.println(
"\nSERVER> "+response);
}
}while (!message.equals("***CLOSE***"));
}
catch(IOException ioEx)
{
ioEx.printStackTrace();
}

2.2

Using Sockets

27

finally
{
System.out.println(
"\n* Closing connection… *"); datagramSocket.close(); //Step 8.
}
}
}
For the preceding application to work, UDP must be installed and working on the host machine. As for TCP/IP, if there is a working Internet connection on the machine, then UDP is running. Once again, in order to start the application, first open two command windows and then start the server running in one window and the client in the other. (Start the server before the client!) As before, the example screenshots in Figs. 2.5 and 2.6 show the dialogues between the server and two clients. Observe the differences in output between this example and the corresponding TCP/IP example. (Note that the change at the client end is simply the rather subtle one of cumulative message-numbering.)

Fig. 2.6 Example output from the UDPEchoClient program (with two clients connecting separately) 28

2 Starting Network Programming in Java

Fig. 2.5 Example output from the UDPEchoServer program

2.3

Network Programming with GUIs

Now that the basics of socket programming in Java have been covered, we can add some sophistication to our programs by providing them with graphical user interfaces (GUIs), which users have come to expect most software nowadays to provide.
In order to concentrate upon the interface to each program, rather than upon the details of that program’s processing, the examples used will simply provide access to some of the standard services, available via ‘well known’ ports. Some of these standard services were listed in Fig. 1.1.
Example
The following program uses the Daytime protocol to obtain the date and time from port 13 of user-specified host(s). It provides a text field for input of the host name by the user and a text area for output of the host’s response. There are also two buttons, one that the user presses after entry of the host name and the other that closes down the program. The text area is ‘wrapped’ in a JScrollPane, to cater for long lines of output, while the buttons are laid out on a separate panel. The application frame itself will handle the processing of button presses, and so implements the
ActionListener interface. The window-closing code (encapsulated in an anonymous
WindowAdapter object) ensures that any socket that has been opened is closed before exit from the program. import java.awt.*; import java.awt.event.*;

2.3

Network Programming with GUIs

import import import import 29

javax.swing.*; java.net.*; java.io.*; java.util.*; public class GetRemoteTime extends JFrame implements ActionListener
{
private JTextField hostInput; private JTextArea display; private JButton timeButton; private JButton exitButton; private JPanel buttonPanel; private static Socket socket = null; public static void main(String[] args)
{
GetRemoteTime frame = new GetRemoteTime(); frame.setSize(400,300); frame.setVisible(true); frame.addWindowListener( new WindowAdapter()
{
public void windowClosing(
WindowEvent event)
{
//Check whether a socket is open… if (socket != null)
{
try
{
socket.close();
}
catch (IOException ioEx)
{
System.out.println(
"\nUnable to close link!\n"); System.exit(1);
}
}
System.exit(0);
}
}
);
}

30

2 Starting Network Programming in Java

public GetRemoteTime()
{
hostInput = new JTextField(20); add(hostInput, BorderLayout.NORTH); display = new JTextArea(10,15);
//Following two lines ensure that word-wrapping
//occurs within the JTextArea… display.setWrapStyleWord(true); display.setLineWrap(true); add(new JScrollPane(display),
BorderLayout.CENTER);
buttonPanel = new JPanel(); timeButton = new JButton("Get date and time "); timeButton.addActionListener(this); buttonPanel.add(timeButton); exitButton = new JButton("Exit"); exitButton.addActionListener(this); buttonPanel.add(exitButton); add(buttonPanel,BorderLayout.SOUTH); } public void actionPerformed(ActionEvent event)
{
if (event.getSource() == exitButton)
System.exit(0);
String theTime;
//Accept host name from the user…
String host = hostInput.getText(); final int DAYTIME_PORT = 13; try {
//Create a Socket object to connect to the
//specified host on the relevant port… socket = new Socket(host, DAYTIME_PORT);
//Create an input stream for the above Socket
//and add string-reading functionality…
Scanner input = new Scanner(socket.getInputStream());
//Accept the host’s response via the

2.3

Network Programming with GUIs

31

//above stream… theTime = input.nextLine();
//Add the host’s response to the text in
//the JTextArea… display.append("The date/time at " + host
+ " is " + theTime + "\n"); hostInput.setText(""); } catch (UnknownHostException uhEx)
{
display.append("No such host!\n"); hostInput.setText(""); } catch (IOException ioEx)
{
display.append(ioEx.toString() + "\n");
}
finally
{
try
{
if (socket!=null) socket.close(); //Close link to host.
}
catch(IOException ioEx)
{
System.out.println(
"Unable to disconnect!");
System.exit(1);
}
}
}
}
If we run this program and enter ivy.shu.ac.uk as our host name in the client’s
GUI, the result will look something like that shown in Fig. 2.7.
Unfortunately, it is rather difficult nowadays to find a host that is running the
Daytime protocol. Even if one does find such a host, it may be that the user’s own firewall blocks the output from the remote server. If this is the case, then the user will be unaware of this until the connection times out—which may take some time!
The user is advised to terminate the program (with Ctrl-C) if the waiting time appears to be excessive. One possible way round this problem is to write one’s own
‘daytime server’…

32

2 Starting Network Programming in Java

Fig. 2.7 Example output from the GetRemoteTime program

To illustrate just how easy it is to provide a server that implements the Daytime protocol, example code for such a server is shown below. The program makes use of class Date from package java.util to create a Date object that will automatically hold the current day, date and time on the server’s host machine. To output the date held in the Date object, we can simply use println on the object and its toString method will be executed implicitly (though we could specify toString explicitly, if we wished). import java.net.*; import java.io.*; import java.util.Date; public class DaytimeServer
{
public static void main(String[] args)
{
ServerSocket server; final int DAYTIME_PORT = 13;
Socket socket; try { server = new ServerSocket(DAYTIME_PORT); do 2.3

Network Programming with GUIs

33

{ socket = server.accept();
PrintWriter output = new PrintWriter( socket.getOutputStream(),true); Date date = new Date(); output.println(date); //Method toString executed in line above. socket.close(); }while (true);
}
catch (IOException ioEx)
{
System.out.println(ioEx);
}
}
}
The server simply sends the date and time as a string and then closes the connection. If we run the client and server in separate command windows and enter localhost as our host name in the client’s GUI, the result should look similar to that shown in Fig. 2.7. Unfortunately, there is still a potential problem on some systems: since a low-numbered port (i.e., below 1024) is being used, the user may not have sufficient system rights to make use of the port. The solution in such circumstances is simple: change the port number (in both server and client) to a value above 1024.
(E.g., change the value of DAYTIME_PORT from 13 to 1300.)
Now for an example that checks a range of ports on a specified host and reports on those ports that are providing a service. This works by the program trying to create a socket on each port number in turn. If a socket is created successfully, then there is an open port; otherwise, an IOException is thrown (and ignored by the program, which simply provides an empty catch clause). The program creates a text field for acceptance of the required URL(s) and sets this to an initial default value. It also provides a text area for the program’s output and buttons for checking the ports and for exiting the program. import import import import import java.awt.*; java.awt.event.*; javax.swing.*; java.net.*; java.io.*;

public class PortScanner extends JFrame implements ActionListener

34

2 Starting Network Programming in Java

{ private private private private private private

JLabel prompt;
JTextField hostInput;
JTextArea report;
JButton seekButton, exitButton;
JPanel hostPanel, buttonPanel; static Socket socket = null;

public static void main(String[] args)
{
PortScanner frame = new PortScanner(); frame.setSize(400,300); frame.setVisible(true); frame.addWindowListener( new WindowAdapter()
{
public void windowClosing(
WindowEvent event)
{
//Check whether a socket is open… if (socket != null)
{
try
{
socket.close();
}
catch (IOException ioEx)
{
System.out.println(
"\nUnable to close link!\n");
System.exit(1);
}
}
System.exit(0);
}
}
);
} public PortScanner()
{
hostPanel = new JPanel(); prompt = new JLabel("Host name: "); hostInput = new JTextField("ivy.shu.ac.uk", 25); hostPanel.add(prompt); 2.3

Network Programming with GUIs

35

hostPanel.add(hostInput); add(hostPanel,BorderLayout.NORTH); report = new JTextArea(10,25); add(report,BorderLayout.CENTER); buttonPanel = new JPanel(); seekButton = new JButton("Seek server ports "); seekButton.addActionListener(this); buttonPanel.add(seekButton); exitButton = new JButton("Exit"); exitButton.addActionListener(this); buttonPanel.add(exitButton); add(buttonPanel,BorderLayout.SOUTH); } public void actionPerformed(ActionEvent event)
{
if (event.getSource() == exitButton)
System.exit(0);
//Must have been the 'seek' button that was
//pressed, so clear the output area of any
//previous output… report.setText(""); //Retrieve the URL from the input text field…
String host = hostInput.getText(); try {
//Convert the URL string into an INetAddress
//object…
InetAddress theAddress =
InetAddress.getByName(host);
report.append("IP address: "
+ theAddress + "\n"); for (int i = 0; i < 25; i++)
{
try
{
//Attempt to establish a socket on
//port i… socket = new Socket(host, i);
//If no IOException thrown, there must
//be a service running on the port…

36

2 Starting Network Programming in Java

report.append(
"There is a server on port "
+ i + ".\n"); socket.close(); } catch (IOException ioEx)
{}// No server on this port
}
} catch (UnknownHostException uhEx)
{
report.setText("Unknown host!");
}
}
}
When the above program was run for the default server (which is on the author’s local network), the output from the GUI was as shown in Fig. 2.8.
Unfortunately, remote users’ firewalls may block output from most of the ports for this default server (or any other remote server), causing the program to wait for each of these port accesses to time out. This is likely to take a very long time indeed! The reader is strongly advised to use a local server for the testing of this program (and to get clearance from your system administrator for port scanning, to be on the safe side). Even when running the program with a suitable local server, be patient when waiting for output, since this may take a minute or so, depending upon your system.

Fig. 2.8 Example output from the PortScanner program 2.3

Network Programming with GUIs

37

Exercises
2.1 If you haven’t already done so, compile programs TCPEchoServer and
TCPEchoClient from Sect. 2.2.1 and then run them as described at the end of that section.
2.2 This exercise converts the above files into a simple email server and email client respectively. The server conversion has been done for you and is contained in file EmailServer.java, a printed version of which appears on the following pages for ease of reference. Some of the code for the client has also been provided for you and is held in file EmailClient.java, a printed version of which is also provided.
You are to complete the coding for the client and then run the server program in one command window and the client program consecutively in each of two further command windows. For the first client, log in with one of the names specified below (i.e., ‘Dave’ or ‘Karen’) and send a few emails (fewer than 10) to the other user. Then quit and run the client program again, this time logging in as the other user and selecting reading of his/her emails. The full details of this simplified client–server application are given below.
• The server recognises only two users, called ‘Dave’ and ‘Karen’.
• Each of the above users has a message box on the server that can accept a maximum of 10 messages.
• Each user may either send a one-line message to the other or read his/her own messages. • A count is kept of the number of messages in each mailbox. As another message is received, the appropriate count is incremented (if the maximum has not been reached). When messages are read, the appropriate count is reduced to zero.
• When sending a message, the client sends three things: the user’s name, the word ‘send’ and the message itself.
• When requesting reading of mail, the client sends two things: the user’s name and the word ‘read’.
• As each message is received by the server, it is added to the appropriate mailbox (if there is room). If the mailbox is full, the message is ignored.
• When a read request is received, the server first sends an integer indicating the number of messages (possibly 0) that will be sent and then transmits the messages themselves (after which it reduces the appropriate message count to 0).
• Each user is to be allowed to ‘send’ and/or ‘read’ as many times as he/she wishes, until he/she decides to quit.
• When the user selects the ‘quit’ option, the client sends two things: the user’s name and then the word ‘quit’.
2.3 If you haven’t already done so, compile and run the server program
DayTimeServer and its associated client, GetRemoteTime, from Sect. 2.3.

38

2 Starting Network Programming in Java

2.4 Program Echo is similar to program TCPEchoClient from Sect. 2.2.1, but has a
GUI front-end similar to that of program GetRemoteTime from Sect. 2.3. It provides an implementation of the echo protocol (on port 7). This implementation sends one-line messages to a server and uses the following components:
• a text field for input of messages (in addition to the text field for input of host name); • a text area for the (cumulative) echoed responses from the server;
• a button to close the connection to the host.
Some of the code for this program has been provided for you in file Echo.java, a printed copy of which appears at the end of this chapter. Examine this code and make the necessary additions in the places indicated by the commented lines. When you have completed the program, run it and supply the name of any convenient server when prompted for a server name. If you don’t have access to a convenient server use localhost, having changed the port number of TCPEchoServer
(Sect. 2.2.1) to 7 and then started that program running.
//For use with exercise 2.2. import java.io.*; import java.net.*; import java.util.*; public class EmailServer
{
private static ServerSocket serverSocket; private static final int PORT = 1234; private static final String client1 = "Dave"; private static final String client2 = "Karen"; private static final int MAX_MESSAGES = 10; private static String[] mailbox1 = new String[MAX_MESSAGES]; private static String[] mailbox2 = new String[MAX_MESSAGES]; private static int messagesInBox1 = 0; private static int messagesInBox2 = 0; public static void main(String[] args)
{
System.out.println("Opening connection…\n"); try { serverSocket = new ServerSocket(PORT);
}
catch(IOException ioEx)

2.3

Network Programming with GUIs

39

{
System.out.println(
"Unable to attach to port!");
System.exit(1);
} do { try { runService(); } catch (InvalidClientException icException)
{
System.out.println("Error: " + icException);
}
catch (InvalidRequestException irException)
{
System.out.println("Error: " + irException);
}
}while (true);
}
private static void runService() throws InvalidClientException,
InvalidRequestException
{ try {
Socket link = serverSocket.accept();
Scanner input = new Scanner(link.getInputStream());
PrintWriter output = new PrintWriter( link.getOutputStream(),true); String name = input.nextLine();
String sendRead = input.nextLine(); if (!name.equals(client1) &&
!name.equals(client2))
throw new InvalidClientException(); if (!sendRead.equals("send") &&
!sendRead.equals("read"))
throw new InvalidRequestException();
System.out.println("\n" + name + " "
+ sendRead + "ing mail…"); if (name.equals(client1))

40

2 Starting Network Programming in Java

{ if (sendRead.equals("send"))
{
doSend(mailbox2,messagesInBox2,input); if (messagesInBox2=0) && (score Control Panel from the bottom left corner of the desktop.
Click on the System and Security sub-heading.
Click on the System sub-heading.
Click on the Advanced system settings link in the left-hand pane.
Click on the Environment Variables… button in the bottom right corner.
Either select Path or CLASSPATH from System Variables and then click on Edit or click on New to create a new environment variable.
7. If adding a new path to Path or CLASSPATH, then either prepend the new path and a trailing semi-colon (;) or append it with a leading semi-colon (;). If creating a new environment variable, simply enter the name of the new variable and its associated path.
8. Click on OK and then again on OK.
For users of earlier versions of the Windows operating system, the steps will be somewhat similar to those given above, the only differences likely to be a reference to Start->Settings->Control Panel in the first step and double-clicking on a System icon in step 2.
For the remainder of this chapter, it is Tomcat that will be used for the execution of servlets.

8.3

Creating a Web Application

To set up your own servlets (and/or JSPs, as explained in the next chapter), you need to create a Web application under Tomcat (or make use of an existing one). To create a new Web application, you need to create the required folder structure immediately below the existing standard folder webapps in the Tomcat folder structure. The main part of the folder structure for a Web application called MyWebApp is:
MyWebApp->WEB-INF->classes
[N.B. Upper-case for ‘WEB-INF’ and lower-case for ‘classes’ are mandatory.]
The rules governing what makes up a Web application and what goes where in such an application are listed below. For convenience, the name of the Web

8.3

Creating a Web Application

229

application here and through the rest of the chapter will be shown as MyWebApp, but this can be any name of your own choosing.
1. Place HTML files and JSPs (covered in the next chapter) within MyWebApp.
2. Place servlets within MyWebApp\WEB-INF. If packages are used, there must be a folder structure within classes to reflect this.
3. Create a file called web.xml within WEB-INF. This file is known as the deployment descriptor and specifies details of the Web application (as described below). In particular, it must contain and tags for each servlet.
The opening lines of the deployment descriptor are always the same and may simply be copied from one Web application to the next. In fact, it is highly advisable to copy these lines (i.e., via a wordprocessor, not by transcribing them), since it is very easy to make a mistake, particularly with the string identifying the XML schema location. The naive user may even place a line break in the middle of this.
The example below shows a deployment descriptor for a Web application containing a single servlet called FirstServlet. The servlet must have and tags that identify the associated Java .class file and the servlet’s
URL location (relative to the web application) respectively. These and tags will have exactly the same structure for any other servlet.
Example

FirstServlet
FirstServlet

FirstServlet
/FirstServlet

Note the use of a ‘/’ in the tag! This is easily omitted.
If any changes are made to servlet tags after Tomcat has started, it will be necessary to stop Tomcat (via shutdown) and re-start it (via startup). This is also necessary after changing any servlet.

230

8.4

8

Servlets

The Servlet URL and the Invoking Web Page

Before we consider the structure of a servlet, recall that a servlet will be executed on a Web server only in response to a request from a user’s browser. Though the servlet may be invoked directly by entering its URL into the browser (an example of which is shown at the end of the previous chapter), it is much more common for a servlet to be called from a preceding HTML page. This is usually achieved by the use of an HTML form, with the form’s METHOD attribute specifying either ‘GET’ or ‘POST’ and its ACTION attribute specifying the address of the servlet. As noted in the previous section, each servlet must be held in folder
\webapps\\WEB-INF\classes. The URL for such a servlet has the following format: http://localhost:8080// For example: http://localhost:8080/MyWebApp/FirstServlet Note the use of localhost above to refer to the current machine and 8080 to indicate that Tomcat uses port 8080. Usually, of course, client and server programs will be on separate machines, but this gives us a convenient test bed for our programs.
The servlet above may then be invoked via the ACTION attribute of a FORM tag in a preceding HTML page as follows:

Note that the URL for the servlet is relative to the Web application that contains both the servlet and the HTML page.
To keep things as simple as possible for the time being, we shall start off with a
Web page that calls up a servlet without actually sending it any data. The code for this simple Web page is shown below.
Example

A First Servlet

body{text-align:center;}

8.5

Servlet Structure

231

Before we look at the output from this Web page, we need to consider just what our servlet will look like…

8.5

Servlet Structure

Servlets must import the following two packages:
• javax.servlet
• javax.servlet.http
As of Tomcat 7, it is also necessary to import the following annotation type:
• javax.servlet.annotation.WebServlet
In addition, since servlet output uses a PrintWriter stream, package java.io is required. Servlets that use the HTTP protocol (which means all servlets, at the present time) must extend class HttpServlet from package java.servlet.http. The two most common HTTP requests (as specified in the HTML pages that make use of servlets) are GET and POST. At the servlet end, method service will despatch either method doGet or method doPost in response to these requests. The programmer should override (at least) one of these two methods.
You should use the POST method for multiple data items and/or items that need to be transmitted securely. If you are transmitting just single items that have no security implications, then use GET. All three methods (doGet, doPost and service) have a void return type and take the following two arguments:
• an HttpServletRequest object;
• an HttpServletResponse object.
The former encapsulates the HTTP request from the browser and has several methods, but none will be required by our first servlet. The second argument holds the servlet’s response to the client’s request. There are just two methods of this
HttpServletResponse object that are of interest to us at present and these are shown below.
• void setContentType(String )
This specifies the data type of the response. Normally, this will be “text/HTML”.
• PrintWriter getWriter()
Returns the output stream object to which the servlet can write character data to the client (using method println).
There are four basic steps in a servlet…
1. Execute the setContentType method with an argument of “text/HTML”.
2. Execute the getWriter method to generate a PrintWriter object.
3. Retrieve any parameter(s) from the initial Web page.
(Not required in our first servlet.)
4. Use the println method of the above PrintWriter object to create elements of the
Web page to be ‘served up’ by our Web server.

232

8

Servlets

The above steps are normally carried out by doGet or doPost. Note that these methods may generate IOExceptions and ServletExceptions, which are checked exceptions (and so must be either thrown or handled locally). Note also that step 4 involves a lot of tedious outputting of the required HTML tags.
Finally, as of Tomcat 7, a WebServlet annotation tag is required before the opening line of the servlet class. This tag indicates the name of the servlet and the path to it (relative to the classes folder) and has the following format:
@WebServlet(“//”)
Example
This first servlet simply displays the message ‘A Simple Servlet’.
[In passing, note that CSS scripts will not work with servlets, and so the conventional HTML tag (not supported in HTML 5) has had to be used below! The same comment applies to the tag in later examples.] import import import import

java.io.*; javax.servlet.*; javax.servlet.http.*; javax.servlet.annotation.WebServlet; @WebServlet("/FirstServlet") public class FirstServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException,ServletException
{
response.setContentType("text/HTML");
PrintWriter out = response.getWriter(); out.println(""); out.println(""); out.println("Simple Servlet"); out.println(""); out.println(""); out.println(""); out.println(
"A Simple Servlet"); out.println(""); out.println(""); out.flush(); }
}
Note the use of method flush of the PrintWriter object to send data out of the object’s buffer.

8.7 Passing Data

233

This servlet should now be compiled in the same way as any other Java program, either by using a development environment or by opening a command window and executing the Java compiler as follows: javac FirstServlet.java

8.6

Testing a Servlet

In order to test our Web page and associated servlet, we first need to set Tomcat running. This may be done either by double-clicking on file startup.bat (in
\bin) or by entering the following command into an MS
DOS command window (assuming that startup.bat is on the PATH): startup Four lines of output should appear in the current command window and a second command window will begin to fill up with output. When the line commencing
INFO: Server startup appears in the second window, Tomcat is running.
Assuming that our initial Web page has been given the name FirstServlet.html, we can now open up our browser and enter the following address: http://localhost:8080/FirstServlet.html Figure 8.1 shows what this initial Web page looks like under the Firefox browser.
Upon clicking on the page’s button, the servlet is executed and the output shown in
Fig. 8.2 is produced.

8.7

Passing Data

The previous example was very artificial, since no data was passed by the initial form and so there was no unpredictability about the contents of the page generated by the servlet. We might just as well have had two static Web pages, with a hyperlink connecting one to the other. Let’s modify the initial form a little now, in order to make the example rather more realistic…

Enter your first name:

Now our form will accept the user’s first name and, once the ‘Submit’ button is clicked, will pass the value entered to the servlet. The servlet may then make use of this value when constructing the page to be returned by the Web server.
It is now appropriate to consider the methods of HttpServletRequest that are responsible for handling values/parameters received by servlets. There are three such methods, as listed below.

234

Fig. 8.1 Button to connect to servlet FirstServlet

Fig. 8.2 Output from FirstServlet under Firefox 1.5

8

Servlets

8.7 Passing Data

235

• String getParameter(String )
Returns the value of a single parameter sent with GET or POST.
• Enumeration getParameterNames()
Returns the names of all parameters sent with POST.
• String[] getParameterValues(String )
Returns the values for a parameter that may have more than one value.
Only the first of these methods is needed for a single parameter sent via GET, which is all we require for our current example. The code below shows our first servlet modified so that it adds the name entered by the user to the greeting that is displayed on the returned page. The code shown in bold type indicates the very few changes made to the original program.
Example
import import import import java.io.*; javax.servlet.*; javax.servlet.http.*; javax.servlet.annotation.WebServlet; @WebServlet("/PersonalServlet") public class PersonalServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws IOException,ServletException
{
response.setContentType("text/HTML");
PrintWriter out = response.getWriter(); out.println(""); out.println(""); out.println("Simple Servlet"); out.println(""); out.println(""); out.println(""); String name = request.getParameter("FirstName"); out.println(" A Simple Servlet for "); out.println(name + ""); out.println(""); out.println(""); out.flush(); }
}
This is what the initial page looks like (after a name has been entered into the text box) (Fig. 8.3):
The servlet-generated page (after the above button has been clicked) is shown in Fig. 8.4.

236

Fig. 8.3 Web page for passing a single data item to a servlet

Fig. 8.4 Servlet output making use of data item received from initial Web page

8

Servlets

8.7 Passing Data

237

One potential problem with this method is that, if the browser’s ‘Back’ button is clicked to return to the opening Web page, the initial name entered is still visible.
This doesn’t really matter in this particular example, but, for other (repeated) data entry, it probably would. In order to overcome this problem, we need to force the browser to reload the original page, rather than retrieve it from its cache, when a return is made to this page. There is an HTML META tag that will do this, but the tag varies from browser to browser. However, the following set of tags will satisfy most of the major browsers:

These should be placed immediately after the tag on the initial
Web page.
Continuing now with the approach of gradually adding to the complexity of our servlets, the next step is to carry out some processing of the data entered and display the results of such processing. The next example accepts two numbers, adds them and then displays the result. Since there are multiple inputs, we shall use the POST method. In addition, an HTML table has been used for laying out the page elements neatly. Example
Firstly, the code for the initial Web page…

Simple Adder

First number

Second number

238

8

Servlets

Since the user may enter a non-numeric value, the servlet must cater for a possible NumberFormatException. In addition, method getParameter will need to convert the strings it receives into integers by using the parseInt method of the Integer wrapper class. Now for the code… import import import import

java.io.*; javax.servlet.*; javax.servlet.http.*; javax.servlet.annotation.WebServlet; @WebServlet("/AdderServlet") public class AdderServlet extends HttpServlet
{
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws IOException,ServletException
{
try
{
String value1 = request.getParameter("Num1");
String value2 = request.getParameter("Num2"); int num1 = Integer.parseInt(value1); int num2 = Integer.parseInt(value2); int sum = num1 + num2; sendPage(response,"Result = " + sum);
}
catch(NumberFormatException nfEx)
{
sendPage(response,"*** Invalid entry! ***");
}
} private void sendPage(HttpServletResponse reply,
String result) throws IOException

8.7 Passing Data

239

{ reply.setContentType("text/HTML"); PrintWriter out = reply.getWriter(); out.println(""); out.println(""); out.println("Result"); out.println(""); out.println(""); out.println(""); out.println(""); out.println("Result=" + result); out.println(""); out.println(""); out.println(""); out.flush();
}
}
Note the convenient dual-purpose use of method sendPage to return either the result page or an error page (Figs. 8.5, 8.6 and 8.7).

Fig. 8.5 Web page receiving two integers to be sent to a servlet

240

8

Servlets

Output from the servlet:

Fig. 8.6 Result of a simple calculation sent back by servlet AdderServlet

8.8

Sessions

One fundamental restriction of HTTP is that it is a stateless protocol. That is to say, each request and each response is a self-contained and independent transaction.
However, different parts of a Web site often need to know about data gathered in other parts. For example, the contents of a customer’s electronic cart on an e-commerce shopping site need to be updated as the customer visits various pages and selects purchases. To cater for this and a great number of other applications, servlets implement the concept of a session. A session is a container where data about a client’s activities may be stored and accessed by any of the servlets that have access to the session object. The session expires automatically after a prescribed timeout period (30 min for Tomcat) has elapsed or may be invalidated explicitly by the servlet (by execution of method invalidate).
A session object is created by means of the getSession method of class
HttpServletRequest. This method is overloaded:
• HttpSession getSession()
• HttpSession getSession(boolean create)

8.8

Sessions

241

If the first version is used or the second version is used with an argument of true, then the server returns the current session if there is one; otherwise, it creates a new session object. For example:
HttpSession cart = request.getSession();
If the second version is used with an argument of false, then the current session is returned if there is one, but null is returned otherwise.
A session object contains a set of name-value pairs. Each name is of type String and each value is of type Object. Note that objects added to a session must implement the Serializable interface. (This is true for the String class and for the type wrapper classes such as Integer.) A servlet may add information to a session object via the following method: void setAttribute(String , Object )
Example
String currentProduct = request.getParameter("Product");
HttpSession cart = request.getSession(); cart.setAttribute("currentProd",currentProduct); The method to remove an item is removeAttribute, which has the following signature:
Object removeAttribute(String )
For example: cart.removeAttribute(currentProduct); To retrieve a value, use:
Object getAttribute(String )
Note that a typecast will usually be necessary after retrieval. For example:
String product =
(String)cart.getAttribute("currentProd");
To get a list of all named values held, use:
String[] getAttributeNames()
For example:
String[] prodName = cart.getAttributeNames();
It’s now time to put these individual pieces together into a full example application… Example
This example involves a simplified shopping cart into which the user may place a specified weight of apples and/or a specified weight of pears. Three servlets are used, for the following purposes:

242

8

Servlets

• selection of apples/pears;
• entry of required weight;
• checking out.
If one servlet needs to transfer execution to another, then method sendRedirect of class HttpServletResponse may be used. The initial HTML page makes use of radio buttons ().

Shopping Cart

Simple Shopping Cart

Apples

Pears

Go to checkout

8.8

Sessions

243

Similar Documents

Premium Essay

Technology

...the living better. Nowadays, technology has advanced in tremendous leaps and bounds. We cannot imagine the world without technological advances such as computer, televisions, machines and so on. However there are some advantages and disadvantages of technology. First of all, technologies play a very important role in society because it makes life easier to live on and less time consuming. Technology has the ability to create shortcuts in working. People do not have to do all the hard labor anymore. For example, microwave ovens cook food easily without using any stoves and making a big mess. Some decade ago, there were no gas or electric stoves, people have to get firewoods and lighting them up for cooking. Technology makes things very easy to use comparing it in the old fashion way. Moreover, medical science is very progressive and saves many innocent lives. Medical treatment has been going well with the help of technology. Nowadays, hospitals use technology as the assistance for the operation. Doctors use machines to produce medicine to cure sickness and the discovery of x-ray enable doctors to treat some kinds of diseases. On the contrary, technology also brings harm to our society. The booming of industrialization and development causes pollutions to our world. For example, the smoke from the vehicles and machines affects the quality of air and destroy the ozone layer. As a result, people suffer illness like cancers. In addition, technologies also create financial problems...

Words: 329 - Pages: 2

Free Essay

Technology

...Advances in technology have brought about changes in almost every part of the world. People from opposite ends of the earth can now be in constant communication. The health industry is making effective use of modern technology, enabling people everywhere to live longer, and healthier lives. Many schools are integrating aspects of modern technology into the classroom. Teachers today have new tools and methods at their disposal, to pass knowledge to students. As a child, I took computers for granted, and could hardly imagine the thought of living without them. This makes me question how the advancement of modern technology could be shaping our lives in many ways for the better, or worse. In 1950, the average life expectancy of a man living in the United States was almost seventy. For the last sixty years that number has increased steadily. A man born in 2014, in the United States, would have a life expectancy of almost eighty years. Many factors likely contributed to the increase in life expectancy. Most pivital, were the advancements made in the study of medicinal technology. Doctors now have access to technology that would have seemed like fantasy, a few years ago. Machines like an x-ray can now look into our bodies, and capture images with great detail. The images can then analyzed by a doctor, and if necessary, immediate action can be taken. As a result of the great deal of information available to doctors today, the need for exploratory surgeries has diminished...

Words: 1171 - Pages: 5

Free Essay

Technology

...Argumentation-Persuasion Essay
People have become overly dependent on technology We are living in a society which is called "technologically civilized" society. Every small work we do is technology dependent. Today every other person is recognized with the device or gadget, he carries; which is technically advanced. Ultimately, we can say that, “living without technology is like living without air" in this technical world of today. Therefore, we are much dependent on technology. Our lifestyles have changed and still continue to change each time a new invention is created. Among the most influential are wheels, light bulbs, telephones, transportation vehicles, refrigerators, radios, televisions, plastics, and computers. The initial purpose of these inventions were to make work easier to do, be able to see in the dark with electricity, communicate more efficiently and quickly, and move all across the world at a faster pace. I am glad we live in a technological society because we can research items quickly by using the internet; communicate with people from great distances within seconds; and carry large and heavy loads on trucks, ships, and airplanes. With this in mind, are we as a society forgetting how privileged we are and taking our lives for granted?
 In the good old days, people were very self-sufficient and created many things from scratch, such as bread, butter, and clothing. Unfortunately, many people today are not taught to do these things because we...

Words: 1369 - Pages: 6

Premium Essay

Technology

...the community being stopped. On the other hand, local residents with small businesses near to Nestle Factories would benefit due to the money being brought in by workers at the factory. Consumers eating less chocolate because of health risks or a seasonal variation in the summer months where Ice Cream is more popular (Ice cream version of the KitKat egg). Consumers spending their disposable income on new technology like mobile phones, computer games and young children spending money on new toy ect. TECHNOLOGICAL – developments in manufacturing and business processes. If the cost of machinery risen due to an increase in cost of producing that machinery means production cocts of the new KitKat will be high than before the increase. There could be new machinery enter the market that allows production to be carried out more effective and efficient than before, which saves on labour costs. Maintenance cost of machinery may increase because better-trained skilled personnel are needed to maintain the machinery through advanced in technology. Employees may need training for advancing IT within the...

Words: 264 - Pages: 2

Free Essay

Technology

...Professor Name Title Date Due The Technology Essay Introduction Technology entails applying the scientific knowledge practically especially in industries. Technology is an item made by man to help with accomplishing some objectives. A technology is a collection of human information that can be gone along starting with one spot then onto the next and starting with one era then onto the next. Technology is an effective compel in our world today. It helps us to create more food than sometime recently, developing building and houses are speedier by cutting edge instruments, successful in communication with better flag and more extensive secured ranges, go to any place in the world. A human will have a great world if innovations do not habitually have adverse reactions. In any case, technology has affected positively to our societies and the risks are worth taking. This paper will give a thorough argument in support of the fact that technology is beneficial and worth taking any risk for it. Technology is Beneficial Technology brings people numerous approaches that ease communication between one another. Communication should be possible through area line telephone, mobile phone, instant messages, email and visit on PCs. Communication technology (rapid web) additionally contributes to medicinal services, working at home, trade, diversion, group, exploration, and instruction. . Mass communication medium is the procedure of conveying and imparting to loads of individuals utilizing...

Words: 1541 - Pages: 7

Premium Essay

Technology

...Technology Technology is a huge part of everyday life for most people. It has made a huge impact on the world today. The question is, how much is too much? While both “No technology? No problem.” By Eric Brende and “Beware the Apps!” by Lacreta Scott are similar in the way they think too much technology is not good but differ in how much they should cut back on. The two articles are similar in the way they both think too much technology is not good. “I am merely wading in technology. They are drowning in it, dog-paddling to keep their heads above water.” (Brende 679) explains here that people are so consumed with technology they are drowning in it. He says “and with a degree of usage, I enjoy a balanced like, blending family with work, and leave ample leisure to write books and articles, play music, and visit relatives.”(Brende679) as he limits his use of technology to a minimum. Lacreta goes on to agree with this “Already I am too late. The apps are with is. Texting, Tweeting, E-mailing, Etc-ing. They are fixtures in our lives.”(Scott683). She starts by telling how it ruins relationships. “I have seen, and you have seen, two people at lunch, talking, but not to each other. Each is talking into a cell phone to absent third parties” (Scott684). She feel that people even miss the little things around them because they are so caught up in technology. “Another common sight is someone walking along, ignoring the sounds of nature or of the city, with a hands-free device in his...

Words: 717 - Pages: 3

Premium Essay

Essay On Technology And Technology

...Technology is Detrimental to Intelligence According to Merriam-Webster, technology is the application of scientific knowledge to other fields of inquiry in order to accomplish a task (“Technology”). Light bulbs, refrigerators, microwaves, and computers are all technology. However, this argument will be focused towards technology with self-luminous screens-computers, laptops, tablets, phones, etc. Self-luminous devices are common in everyday life and affect many spheres of life. One sphere affected is intelligence. Technology has a definite impact on intelligence; the impact is negative. Although technology improved human standard’s of life, technology is detrimental to intelligence because technology increases multitasking, technology creates...

Words: 1146 - Pages: 5

Free Essay

Technology

...Introduction. TECHNOLOGY ! I.1 What is technology? I.2 First Inventors I.3 How science affects technology I.4 Discussion questions I.1 What is technology? Think for a moment what it might be like to live in the 14th century. Image that you could travel back in time and found yourself in a small European village in 1392. What do you think you would find? How would you cook your food? Would you use an oven, a fire, or a microwave? How would you eat your food? Do you think you could use a plastic cup to drink your milk? How would you go from one city to the next? Could you get on a train or would you have to walk or ride a horse? How would you send a message to your mom telling her you’ll be late for dinner? Can you email her or call her on your cell phone? Do you think you could find pink spandex shorts or would they have to be made of brown cotton? Think for a moment how different everything would be if you were to live in the 14th century.Many of the items you use today are a result of technology. Your cell phone, microwave oven, washing machine, and plastic cup are all the result of scientific discoveries combined with engineering that have allow people to invent products that have improved the way people live. Technological advances have improved our health, the food we eat, the clothes we wear, how we travel, and how we communicate with one another. There are a few drawbacks to some aspects of technology but overall technology has greatly improved many...

Words: 1315 - Pages: 6

Free Essay

Technology

...As technology advancing with each generation, handheld devices, personal computers and TV’s have become part of everyone’s life. Even toddlers are now seen using these devices. Is it really beneficial to children using these devices? Will it affect their development? The article “The Touch-Screen Generation” by Hanna Rosin in The Atlantic Monthly magazine (2013), the author mentions the positive and negative influence of allowing children to use technology by giving different people’s views and surveys taken by experts. However. I believe that young children should be allowed to use technology because of the educational apps, ebooks, Children’s are attracted to technology as toys nowadays and they should be allowed to play and learn with it as mentioned by Rosin in the article “more than 40,000 kids’ games are available on iTunes, plus thousands more on Google Play”. Apps like “Noddle words”, “Letter school” teaches children how to write and spell words. With every generation, childhood has changed and as Maria Montessori’s quote says “The hands are the instruments of man’s intelligence”, small children can also learn new things as we adults learn with the use of technology. My cousin sister, about 4 year old, plays a game on her Ipad “Endless Alphabet” which has over 50 words to learn and play with, and word games teaches children letters. Therefore technology is beneficial to children in education. Technology brings many different ways for children to learn. Television shows...

Words: 855 - Pages: 4

Free Essay

Technology

...Why is technological superiority especially significant for international firms? Technology: The technology of a society is the mix of the usable knowledge that the society applies and directs toward the attainment of cultural and economic objectives; it exists in some form in every cultural organization. Technology surely plays a vital role in business today. Businesses have become reliant on technology and if it didn’t exist, almost all business operations around the world could not function. Technology is used in all industries extending from the most basic to the most complex of operations. Commerce and trade around the world most definitely is thriving because of technology. Long before there were computers the world has been doing business; starting from the simple concept of barter trade when the concept of a currency was not yet introduced but trade and commerce was still slow up until the point when the computer revolution changed everything. Technology is used for Point of Sales systems, information management systems capable of handling all kinds of information such as employee profile, client profile, accounting and tracking, automation systems for use in large scale production of commodities, package sorting, assembly lines, all the way to marketing and communications. It doesn't end there, all these commodities also need to be transported by sea, land, and air. According to Ball, “Technological superiority is the goal of most companies, of course, but it is especially...

Words: 427 - Pages: 2

Premium Essay

Technology

...Science and technology have done more harm than good. There is no doubt that science and technology affected our lives. There are a lot of scientists who are working on different science and modern technology projects these days. However, with the new science and technology developments most people underestimate the damage it gives us. First of all, I would like to say, that with these new science and technical appliances people became to be lazy. They rarely go out to work on foot or by a bicycle. Now there are a lot of modern cars in the cities, which are said to be emitting less gas. But still their emitted gasses damage the environment, so to my mind, that is why pollution of our environment is increasing. Secondly, it seems to me, that technologies are throwing away our free time. For example, these new laptop computer or those touch-screen devices are full of entertaining programs, which are attracting people effectively. Then people forget how to communicate with others in real life, not through international communication systems like “Skype” or “Facebook”. On the other hand, my opinion is that science and technology has far increased by the past few decades. New medical treatment, new computer technologies and other useful technical appliances are helping people to solve variety of problems more easily than it used to be. Overall, these new science and technology inventions harm not only our environment, but even us. So in my view, we should start thinking what technologies...

Words: 254 - Pages: 2

Free Essay

Technology

...Technology Technology is defined as ”the sum of knowledge of the means and methods of producing goods and services”. (kilde)Technology is hugely based on science, where scientists’ discover new ways of producing products and services, where they are innovative in their process of making the world more efficient, and also to make life easier for everyone. The world has had massive changes when it comes to technology, especially in the computer industry, where Internet is used all around the world, which has had an effect of a more global community. This helps countries to participate in the world community and to share their products or services. Technology changes lead to the introduction of new products, changes in methods and changes is in the quality of products and resources(kilde bok). Without new technology the world would be less efficient. So in this text I want to focus on the impact the computer industry has had to the world when it comes to advertising, and different types of computer programmes to help the world communicate on a global basis, both positive and negative. Positive- globalt, effektivt, informasjon, Negative- porno, spillavhengighet, plagiat, The computer industry has, as I have mentioned, had a massive affect on businesses all over the world. You are sort of addicted to be available to a computer, or a smartphone, since almost all of the businesses in the world use this technology now. Either it is Email, Facebook, Skype or other programmes...

Words: 346 - Pages: 2

Free Essay

Technology

...Modern Technological Devices Name: Course: Tutor: Date: Outline 1. Introduction 2. Body 3. Conclusion Modern technology is a product of an advanced old technology. It involves advanced communication and transport system. The current world has undergone diverse technological changes that have led to both positive and negative contributions to individuals’ lives. However, I agree that modern technological elements have contributed immensely towards making individuals’ lives easier than in the past because they have led to expansion of business transactions, increased social media marketing, and advanced the quality of education offered in schools. Modern technological elements have helped in the reduction of the effort put by people in carrying out daily activities. In the olden days, life was so challenging, students experienced difficult times in libraries searching for relevant studying materials. However, with the current availability of computers and internet, students carry out their research online. In addition, many relevant materials that can be of great aid to an individual carrying out research get posted online in form of eBooks, articles and journals. Sites such as Wikipedia also play significant roles in providing adequate information for utilization by researchers (Hanks, 88). Technological advancements also increase rate of innovation and creativity in individuals because they pose great challenge to individuals. In olden days...

Words: 903 - Pages: 4

Premium Essay

Technology

...Human life used to be simple and natural but technology has become an essential part of our live in this day and age. Technology gives people a bigger, better and brighter future because it makes tasks easier, quicker and more efficient. With technological machines people are getting help in different sectors, such as transportation, information searching and communication. Firstly, transportation is being convenient; people can go to anywhere they want in a short time by cars, planes and superfast trains. In the past, Japanese used horses to draw a cart to transport people on land. However, railways are all over Japan now and they connect towns along the coast or in the mountains and big cities. Technology has successfully reduced distance between cities and countries. Secondly, computers and the Internet are providing information in the simplest way. Without going to book shops, libraries or wasting time to check dictionaries and to ask somebody, any kind of information on any topic under the sun is available on the Internet. The searching engines like Google, Yahoo are at people’s service on the Internet. They are ready for giving people professional help in any time and any place. Thirdly, the communication technology has been changing to match people’s needs. Smoke, pigeons and letters were replaced with fax and email but today, telephones, mobiles, text messages, email, Internet chat programs are commonly used to communicate and to work. Social networking has...

Words: 510 - Pages: 3

Premium Essay

Technology

...Name: Mohammad yaseen Technology changes our society Technology is the usage and knowledge of tools, machines, techniques, crafts, systems, and methods of organization, in order to solve a problem, accomplish goals or perform a specific function. It can also refer to the collection of such tools, including machinery, modifications, arrangements and procedures. This new innovation comes with both advantage and disadvantages. Technologies significantly affect human as well as animal species' ability to rule and adapt to their natural environments. Nowadays technology in general has made life simpler and keeps people in touch even though they are thousands of miles away from each other (Technological Advancement). Technology can a communication revolution, information technology and it helps the world for a better living in the future. Technology has become a very important part of our lives nowadays. During the past few years, technology has evolved in many ways and is probably without a doubt better than ever before. People are always trying to invent something new that will enhance our lives dramatically. Some major creations that have changed our lives are e-mail, supercomputer, telephone, internet, television, cell phone and voice mail. On the firsthand how technology helps people communicate more information to more people in less time is what student need to experience, it has a greater accuracy and less misunderstandings situations. In this brief lesson, students...

Words: 1121 - Pages: 5