Free Essay

Technology

In: Social Issues

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

...Running head: Technology and Management Technology and Management The latest technology can be seen on sales floor and in offices. Innovations in technology have improved operations at companies of all sizes and helped turn small local businesses into global businesses. Coming from the state of Maine, a retail store Laurie Rodriguez used to work had more than 200 retail stores in the New England area. Working in retail, one must expect the same from each store and to mainly focus on Customer Service. The use of wireless phones has become like a lifeline as much as a necessity because salespeople continually call to know when to deliver products. There is a wireless service that is installed in all stores and is at the point of sale registers, without these, manual is no longer among options, customers want to be out fast and efficiently, these point of sale registers allow for the effectiveness of the customer’s wish, standing in line at a register does not increase sales, or improve the business, but only decreases a little. These devices are lifelines when the store is overrun with shoppers, which seems to be just about every day. Staying in touch when on the road and responding to customer inquiries in a timely manner should be a must, when using cell phones, e-mail, text messaging and social networking’s and other advances in communication will keep small businesses connected to their customer bases and improve communication within the company (Kooser, 2011).......

Words: 1220 - Pages: 5

Premium Essay

Technology

...Student name, Professor name, Course information, Submission date The advantages and disadvantages of technology Technology has offered a lot of advancements and improvements to our globe for over the years. Technology is a science applied to practical purposes. Nowadays, technology is not just limited to computers but it advances in the form of cars, microwaves, cell phones and many more. As technology has progressed a lot, this is becoming the fact that it has penetrated almost every aspect of our daily lives from business to leisure. Now we have entered an era where a frequent question revolves in our mind whether technology is saving our ruining the globe? Therefore, here I will present the advantages and disadvantages of technology simultaneously. One of the basic advantages of technology is the globalization, now we are not living in isolation but the world is now becoming a global village. The barriers of language and geographical boundaries are not hindering the knowledge of one continent to be spread globally with the means of technology. However, this massive ocean of knowledge sometimes raises the question for the authenticity of knowledge to be utilized. This would be considered as one of its disadvantage. Technology has also advanced our means of communication to a greater extend. As communication around the globe has became cheaper, quicker and more efficient. Thus now we are given the privilege to use text messaging and......

Words: 549 - Pages: 3

Premium Essay

Technology

...Technology has made life easier for people and it is now becoming something that people rely on too much. In today’s world technology is seen everywhere you go, you can see it in a workplace, schools, public places and in our homes. Technology is a great thing as long as people remember to use it as a tool and not a way of life. Because people rely on technology, it has caused problem like loss of work, vehicle accidents, and lack of proper communication. People should know how to live without fully relying on technology and sadly, not many do know how to live without it. People will argue that technology is the future and that people need to know how to use it to live. Workplaces will argue that technology has improved productivity and reduced costs. Schools will argue that technology has made learning easier for most students and it is something they need to learn to be ready for life outside of school. Most people will just simply argue that they cannot live without technology. These are all good points and yes because of technology, we have been able to get more work done in less time. Sure technology can do the work faster and with fewer mistakes as a person and learning how to use technology is something that everyone needs to know. However, we have relied too much on technology and the question should not be can you live without technology, the question should be, do you know how to live without technology. Today’s jobs mostly run on technology and less by humans....

Words: 1199 - Pages: 5

Premium Essay

Technology

...unless it was monumental or important. However, one thing you would be able to retrace is whom you were talking to at the time, and even what you were talking to them about. With todays technology it makes it very easy to relive past conversations and go back to recorded moments. With modern day advances, individuals hold the ability to be able to capture a moment at anytime and share it around the world with whom they choose. We are also able to play games, entertain ourselves, see others, and talk to our friends at a single push of a button within just a couple of minutes. Technology continues to grow within industries making it easier to communicate and stay organized all due to a tiny handheld gadget. The better the technology the easier it is for people to stay connected with each other. Although there have been several groundbreaking inventions in history, it is noticed that the cell-phone has had a noticeable impact on society, especially among todays youth. With children now gaining access to a variety of these devices it is apparent that many lack basic elements in communicating. With a participant group of roughly twenty-five people, each student was asked to perform an “E-Fast” where the group would go certain amount of time restricting themselves from different forms of technology. Under the “E-Fast” and outside research it was noted that unlimited access to texting, and social media sights could result in a great amount of miscommunication between users. Both......

Words: 1966 - Pages: 8

Premium Essay

Technology

...Technology: It’s Effect on Our Youth Growing up I remember playing outside all day, enjoying the outdoors, and riding bikes down the dirt roads, trying to find some new adventure to get into. Looking around now, I notice teenagers glued to their phones when they are out eating, walking around and even while driving. It seems like a lot has changed since I was a child. Technological advances have made our way of life easier by making communication faster than ever before, improving production rates, and making it easier to access information. However, with the good also comes the bad. I have noticed an increase in the time children spend inside, as opposed to outdoors, the changes in behavior of children and teenagers, and the decline in personal interaction. I believe that technology, if not used in moderation, could have a negative influence on our youth. I have noticed the significant change that has occurred in technology in just a generation’s time. As a child, I remember when people were purchasing their first personal computers, usually for everyone in the household to share. These computers were not nearly as fast and advanced as computers are today. Now, nearly every home in America has a personal computer, laptop or some other way of accessing the internet, like a smartphone or tablet. While access to the internet can help educate children if used in an educational way, misuse of technology, like playing violent video games, could cause a......

Words: 889 - Pages: 4

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

Premium Essay

Technology

...something new that always is going to affect any career that you are taking. My major right now is Business Management and I think technology is changing everybody around the world. There are some technology that can have a big impact in your career because you never know what is up there waiting for you after you are done career in college. Technology has come a long way since it was first made. It has improved in many different ways. It has help thousands of business launch and have a big impact on the community. We need technology, and yet every new technology places new demands upon us and creates new forms of stress. We can't live with it but at the same time we can't live without it. There is no turning back to some pre technical era. They help them in many ways, some were good and some were bad. But for the most part the help of been able to launch off has had a big impact. There are some technology’s that benefits a lot career. Since technology was invented many business have a lot benefits from it and as information travels faster and faster and more reliably, barriers of distance disappear, and businesses are realizing how easy it is to outsource jobs overseas again the Radio frequency identification technology is infiltrating and changing business significantly in a few ways, one begin to tighten security at their organization place. Technology has great effects in businesses. Like using a computer, you can access the Internet and promote your business to the......

Words: 275 - Pages: 2

Free Essay

Technology

...technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology technology ......

Words: 2899 - Pages: 12

Premium Essay

Technology

...Will 2015 be the year of wearable technology? * Article * Wearable technology = smart watches (Apple), use a headset to participate in virtual worlds (Oculus Rift), pay for purchases using a heartbeat reading wristband (Nymi which uses heartbeat as a password), & controlling the computer communicating with a wave from an armband (Myo to use arm gestures to flip through presentations, play games, or music players) * Eventually, headsets will allow sensors to connect to other parts of the body as well * Entering in access codes or passwords wastes time, creates bad experiences, & indulge in wasted energy trying to keep up with different passwords & pins or replacing them * Could lead to poorer controls * Technology is changing to tend to our needs by providing a more natural experience * Focus more on useful, entertaining & personal experiences * Very intuitive, easy & natural for people * User friendly, will tend to older generations that aren’t capable of knowing the ways of technology, as well as for mentally or physically impaired individuals * http://www.wired.com/2013/12/wearable-computers/all/ * Wearable technology replaces the power of smartphone by increasing accessibility, without the hardships of taking your smartphone out of your pocket or stopping you while doing activities (bicycle, swimming, hiking, skiing) * Wearable revolution could take......

Words: 1843 - Pages: 8

Premium Essay

Technology

...How technology has changed the world? Technology is the present world. It affects people’s daily lives. Whether it inspires somebody to be the master at videogames or makes somebody a computer hacker. It has changed the generation of teenagers/young adults rapidly. It has made the generation more greedy, ignorant, and lazy. For instance, my parents did not have fancy cell phones or high-tech computers back then because it was never created. They only had a bike and ball until it was worn out. They never thru a fit for not getting what they wanted or sat at home, playing videogames for numerous hours. They would always be outside, whether the weather was hot or cold, playing soccer or having a snowball fight with their friends. And when they didn’t want to go outside, they sat down, read a book, played cards, or even drank hot cocoa. Now a day, it’s all about getting an iPod touch or a phone with a touch screen. Soon, people will have chairs that will fly around to get a soda from the fridge so they don’t have to get their butt up and walk. Though there seems to be more negative influence of technology, there may still be some silver lining. Technology is taking over our world. People don’t realize what it is doing. In the music industry for instance, when a new song comes out by a famous rock star wearing a metal jacket with no shirt on and multiple piercings, people end up coming to school dressed the same way. They would say to their parents, “It’s the new style at......

Words: 651 - Pages: 3

Free Essay

Technology

...“Technologies have become ubiquitous in our everyday lives,leaving very few sectors untouched.”(Nelson,2001,p.4)It transforms the way people communicate. It has a significant influence on people and society.There is no denying that it brings convenience to people,such as easy to keep touch with each other,finding old friends and make new friends.These are technological breakthroughs, but these also create disastrous effect on people and society,like reducing face-to-face communication,being lazier etc. Nowadays,the way of communication is multifarious .The Internet becomes the main way of communication.There were only two choice for people to communicate with each other——“One was to personally take the trouble to travel to their relatives' place and another would be sending letters.”(How Has Technology Affected Your Life?,n.d,p1) Now,people don’t need to do that anymore.It means they don’t have to wait for a long time for the sake of the other people’s response.Modern technology has totally made convenience for people to keep touch with family and friends at anywhere.Especially for the people who stay away from the home ,they can interact with their friends through the social networking websites,mobile phone ,computer etc.Wherever they are,just send a new twitter,their friends will know about what’s happening now.It is really convenient and fast.At this moment ,they must really thankful to the person who created these products.They can never bear the suffering of the......

Words: 606 - Pages: 3

Premium Essay

Technology

... Technology has brought many benefits and challenges to the business world. The list is endless for the amount of information transported into marketplace every day, changing the way businesses react to what other companies are doing. Technology creates new technologies every two years offering new method of communications. Talking on the cell phone, text, email, and online are some parts of communication with technology of today, businesses use technology to reach the people. As technology continues to move forward it is important to understand the significance of technology in education, business, and personal uses of communication. Many technologies have been developed to assist in the increased productivity in the workplace. During the late 19th century, the business world communication with radio broadcasting, television, newspapers, magazines and mailing of letters used to reach the general public. The ability to reach large segments of the public is of great value to small and large businesses everywhere. To deliver communication products that are specifically designed to meet the goal of attracting large audiences. Most products like newspapers and magazines are sold directly to the reader. “Television is the primary source of market for 78 percent of businesses, compared with 15 percent for radio and only 3 percent for the Internet. Businesses were introduced to new technology online services for people who use computers. There are a number of mediums used when......

Words: 757 - Pages: 4

Free Essay

Technology

...Reflexes and More Vacuous Our nation changes and improves every year, and one of the many improvements that continues to evolve is computer technology. It becomes more prominent and is changing the generations of teenagers and adults as it continues to become more popular. Many can argue that computer technology is good or bad for our minds. Nicholas Carr has shared his view that technology is making our minds vapid. He states at the end of his article “Is Google Making Us Stupid?”, “as we come to rely on computers to mediate our understanding of the world, it is our own intelligence that flattens into artificial intelligence” (345). However along with all the advancements that can help our nation there are also a few technologies such as social media and gaming that does not exactly help improve our generation. Technology may be improving to be fulfilling the wants of people, however our nation needs a generation that does not spend their entire life on the internet. Therefore, social media or gaming is a drawback to computer technology because it begins to prevent people from using their full ability of brain power which will soon prevent from furthering technology in our world to better the nation. The internet and social media have benefited people by improving the knowledge that people have. Many great advances can come out of technology, because just thirty years ago our nation did not even know about the internet. However nowadays, it is used on a daily basis to......

Words: 1206 - Pages: 5

Free Essay

Technology

...Nowadays, technology is transforming the way we live, work, learn and play. Although the growing number of people complain that resource shortage and environmental pollution become serious due to the development of technology, it is undeniable that technology has made the world a better place to live. In my opinion, technology has made people's lives more comfortable. Firstly, the communication between people is becoming faster and easier. Using the internet,we can make friends from different countries and share our feelings with them online. Also, we can send E-mails to our friends in a few minutes Instead of writing letters or sending postcards, the Internet enables us to send E-mails to our friends in a few minutes and know the latest information worldwide immediately. Secondly, technology has made our lives more and more convenient. For example, at the beginning, people used to travel on foot which would take them a great amount of time and energy. But now we have cars, airplanes and high-speed trains which make our journey faster and more comfortable. With the help of modern transportation vehicles , people can go everywhere they prefer to. Finally, advanced medical treatment and technology lengthen people’s life.For example, at the stone age, our ancestors’ average age was about 25. However, after people discovered the mysteries of gene, many deceases which were considered detal before can now be treated and cured. Now people’s average age is two or three......

Words: 271 - Pages: 2

Free Essay

Technology

...Technology. Com/156 1/14/2012 By: Raymond Price I. Introduction In today’s world technology has come a long way in helping people: examples of these ways are phones, medical, internet, science, machines, engineering, computers, and social media. Technology has made the world much easier place to live in. Not only has technology made the world easier to live in, it is now much safer and more comfortable than ever. The technology field is always making challenges for us to do as we grow towards more on a everyday basis. Technology has change us many ways too. The question to ask is. Why is Technology is so important us around the world? The phones that we use in our everyday life has become a lot smarter and become more easier to use in our home or we just out and about. We use this technology over a radio link or a wave and by this we move around a wide spread geographic area. There are some variety of service and some examples of these are text messaging, emails, sending pictures, and the last one is the best part of this is having internet access. The smart phones know days come with some software and application on them to use such as some examples of this are GPS navigation, MP4, MP3 playback, and the last one is a video recording. Why would you ask question to yourself is? How come this company’s are making the cell phones smarter for to use is to help us out if a problem that came up in our life such as example having wreck with your car. There......

Words: 1498 - Pages: 6

Mens Genuine Leather Bifold Zipper Zip Around Wallet Brown Window ID Credit Card | Me My Pets Collier de Chien/Chiot/Chat en Cuir Doux Marron – Choix de Taille | Mirror #1