0% found this document useful (0 votes)
102 views

BITH261 Network Programming

Uploaded by

Etie Kamondo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
102 views

BITH261 Network Programming

Uploaded by

Etie Kamondo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 121

Bachelor of Information

Technology

Network Programming

Module BITH261
Adapted By: Zano Collen

MSc Computer Science (UZ)

BSc (Hons) Computer Science (MSU)

Edited By: Kadanda Constance

MA in Distance Education (IGNOU)

Postgraduate Diploma in Distance Education (IGNOU)

GradCE (UZ)

BA Gen(Hons)(UZ)

ii
Published by: The Zimbabwe Open University

P.O. Box MP1119

Mount Pleasant

Harare, ZIMBABWE

The Zimbabwe Open University is a distance teaching and open


learning institution.

Year: 2017

Cover Design: B. Pillay

Printed by: ZOU Press

Typeset in Garamond, 12 point on auto leading

© Zimbabwe Open University. All rights reserved. No part of this publication


may be reproduced, stored in a retrieval system, or transmitted, in any form or by
any means, electronic, mechanical, photocopying, recording or otherwise, without the
prior permission of the Zimbabwe Open University.
To the student
The demand for skills and knowledge academics, technologists and
and the requirement to adjust and administrators of varied backgrounds,
change with changing technology, places training, skills, experiences and personal
on us a need to learn continually interests. The combination of all these
throughout life. As all people need an qualities inevitably facilitates the
education of one form or another, it has production of learning materials that
been found that conventional education teach successfully any student, anywhere
institutions cannot cope with the and far removed from the tutor in space
demand for education of this magnitude. and time. We emphasize that our
It has, however, been discovered that learning materials should enable you to
distance education and open learning, solve both work-related problems and
now also exploiting e-learning other life challenges.
technology, itself an offshoot of e-
commerce, has become the most To avoid stereotyping and professional
effective way of transmitting these narrowness, our teams of learning
appropriate skills and knowledge materials producers come from different
required for national and international universities in and outside Zimbabwe,
development. and from Commerce and Industry. This
openness enables ZOU to produce
Since attainment of independence in materials that have a long shelf life and
1980, the Zimbabwe Government has are sufficiently comprehensive to cater
spearheaded the development of for the needs of all of you, our learners
distance education and open learning at in different walks of life. You, the
tertiary level, resulting in the learner, have a large number of optional
establishment of the Zimbabwe Open courses to choose from so that the
University (ZOU) on 1 March, 1999. knowledge and skills developed suit the
career path that you choose. Thus, we
ZOU is the first, leading, and currently strive to tailor-make the learning
materials so that they can suit your
the only university in Zimbabwe entirely
personal and professional needs. In
dedicated to teaching by distance
developing the ZOU learning materials,
education and open learning. We are
we are guided by the desire to provide
determined to maintain our leading
you, the learner, with all the knowledge
position by both satisfying our clients
and skill that will make you a better
and maintaining high academic performer all round, be this at certificate,
standards. To achieve the leading diploma, undergraduate or postgraduate
position, we have adopted the course level. We aim for products that will settle
team approach to producing the varied comfortably in the global village and
learning materials that will holistically competing successfully with anyone. Our
shape you, the learner to be an all-round target is, therefore, to satisfy your quest
performer in the field of your own for knowledge and skills through
choice. Our course teams comprise distance education and open learning
Any course or programme launched by ZOU is you may never meet in life. It is our intention
conceived from the cross-pollination of ideas to bring the computer, email, internet chat-
from consumers of the product, chief among rooms, whiteboards and other modern methods
whom are you, the students and your employers. of delivering learning to all the doorsteps of
We consult you and listen to your critical analysis our learners, wherever they may be. For all these
of the concepts and how they are presented. We developments and for the latest information on
also consult other academics from universities what is taking place at ZOU, visit the ZOU
the world over and other international bodies website at www.zou.ac.zw
whose reputation in distance education and open
learning is of a very high calibre. We carry out Having worked as best we can to prepare your
pilot studies of the course outlines, the content learning path, hopefully like John the Baptist
and the programme component. We are only prepared for the coming of Jesus Christ, it is my
too glad to subject our learning materials to hope as your Vice Chancellor that all of you,
academic and professional criticism with the will experience unimpeded success in your
hope of improving them all the time. We are educational endeavours. We, on our part, shall
determined to continue improving by changing continually strive to improve the learning
the learning materials to suit the idiosyncratic materials through evaluation, transformation of
needs of our learners, their employers, research, delivery methodologies, adjustments and
economic circumstances, technological sometimes complete overhauls of both the
development, changing times and geographic materials and organizational structures and
location, in order to maintain our leading culture that are central to providing you with
position. We aim at giving you an education the high quality education that you deserve. Note
that will work for you at any time anywhere and that your needs, the learner ‘s needs, occupy a
in varying circumstances and that your central position within ZOU’s core activities.
performance should be second to none.
Best wishes and success in your studies.
As a progressive university that is forward
looking and determined to be a successful part
of the twenty-first century, ZOU has started to
introduce e-learning materials that will enable
you, our students, to access any source of
information, anywhere in the world through
internet and to communicate, converse, discuss _____________________
and collaborate synchronously and Prof. Primrose Kurasha
asynchronously, with peers and tutors whom Vice Chancellor
The Six Hour Tutorial Session At
The Zimbabwe Open University
A s you embark on your studies with the Zimbabwe
Open University (ZOU) by open and distance
learning, we need to advise you so that you can make
This is where the six hour tutorial comes in. For it
to work, you need to know that:
· There is insufficient time for the tutor to
the best use of the learning materials, your time and
the tutors who are based at your regional office. lecture you
· Any ideas that you discuss in the tutorial,
The most important point that you need to note is originate from your experience as you
that in distance education and open learning, there work on the materials. All the issues
are no lectures like those found in conventional raised above are a good source of topics
universities. Instead, you have learning packages that (as they pertain to your learning) for
may comprise written modules, tapes, CDs, DVDs discussion during the tutorial
and other referral materials for extra reading. All these
· The answers come from you while the
including radio, television, telephone, fax and email
can be used to deliver learning to you. As such, at tutor’s task is to confirm, spur further
the ZOU, we do not expect the tutor to lecture you discussion, clarify, explain, give
when you meet him/her. We believe that that task is additional information, guide the
accomplished by the learning package that you receive discussion and help you put together full
at registration. What then is the purpose of the six answers for each question that you bring
hour tutorial for each course on offer? · You must prepare for the tutorial by
bringing all the questions and answers
At the ZOU, as at any other distance and open that you have found out on the topics to
learning university, you the student are at the centre the discussion
of learning. After you receive the learning package, · For the tutor to help you effectively, give
you study the tutorial letter and other guiding him/her the topics beforehand so that in
documents before using the learning materials. During cases where information has to be
the study, it is obvious that you will come across gathered, there is sufficient time to do
concepts/ideas that may not be that easy to understand so. If the questions can get to the tutor
or that are not so clearly explained. You may also at least two weeks before the tutorial,
come across issues that you do not agree with, that that will create enough time for thorough
actually conflict with the practice that you are familiar preparation.
with. In your discussion groups, your friends can bring
ideas that are totally different from yours and In the tutorial, you are expected and required to
arguments may begin. You may also find that an idea take part all the time through contributing in every
is not clearly explained and you remain with more way possible. You can give your views, even if
questions than answers. You need someone to help they are wrong, (many students may hold the same
you in such matters. wrong views and the discussion will help correct
The Six Hour Tutorial Session At The Zimbabwe Open University

the errors), they still help you learn the correct thing as the tutor may dwell on matters irrelevant to the
as much as the correct ideas. You also need to be ZOU course.
open-minded, frank, inquisitive and should leave no
stone unturned as you analyze ideas and seek
clarification on any issues. It has been found that Distance education, by its nature, keeps the tutor
those who take part in tutorials actively, do better in and student separate. By introducing the six hour
assignments and examinations because their ideas are tutorial, ZOU hopes to help you come in touch with
streamlined. Taking part properly means that you the physical being, who marks your assignments,
prepare for the tutorial beforehand by putting together assesses them, guides you on preparing for writing
relevant questions and their possible answers and examinations and assignments and who runs your
those areas that cause you confusion. general academic affairs. This helps you to settle
down in your course having been advised on how
Only in cases where the information being discussed to go about your learning. Personal human contact
is not found in the learning package can the tutor is, therefore, upheld by the ZOU.
provide extra learning materials, but this should not
be the dominant feature of the six hour tutorial. As
stated, it should be rare because the information
needed for the course is found in the learning package
together with the sources to which you are referred.
Fully-fledged lectures can, therefore, be misleading

The six hour tutorials should be so structured that the


tasks for each session are very clear. Work for each
session, as much as possible, follows the structure given
below.

Session I (Two Hours)


Session I should be held at the beginning of the semester. The main aim
of this session is to guide you, the student, on how you are going to
approach the course. During the session, you will be given the overview
of the course, how to tackle the assignments, how to organize the logistics
of the course and formation of study groups that you will belong to. It is
also during this session that you will be advised on how to use your
learning materials effectively.
The Six Hour Tutorial Session At The Zimbabwe Open University

Session II (Two Hours)


This session comes in the middle of the semester to respond to the
challenges, queries, experiences, uncertainties, and ideas that you are
facing as you go through the course. In this session, difficult areas in the
module are explained through the combined effort of the students and
the tutor. It should also give direction and feedback where you have not
done well in the first assignment as well as reinforce those areas where
performance in the first assignment is good.

Session III (Two Hours)


The final session, Session III, comes towards the end of the semester.
In this session, you polish up any areas that you still need clarification on.
Your tutor gives you feedback on the assignments so that you can use
the experience for preparation for the end of semester examination.

Note that in all the three sessions, you identify the areas
that your tutor should give help. You also take a very
important part in finding answers to the problems posed.
You are the most important part of the solutions to your
learning challenges.

Conclusion for this course, but also to prepare yourself to


contribute in the best way possible so that you
In conclusion, we should be very clear that six can maximally benefit from it. We also urge you
hours is too little for lectures and it is not to avoid forcing the tutor to lecture you.
necessary, in view of the provision of fully self-
contained learning materials in the package, to BEST WISHES IN YOUR STUDIES.
turn the little time into lectures. We, therefore,
urge you not only to attend the six hour tutorials ZOU
BLANK PAGE
Table of Contents
Table of Contents ............................................................................................................. iii
Table of Figures ............................................................................................................. viii
Module Overview ............................................................................................................. ix
Course Objectives............................................................................................................. ix
Course Synopsis ............................................................................................................... ix
General Knowledge .......................................................................................................... xi
Reference Material ........................................................................................................... xi
Unit 1 Introduction to Java Language .................................................................................... 1
1.0 Introduction ............................................................................................................ 1
1.1 Objectives ............................................................................................................... 1
1.2 Java Background ..................................................................................................... 1
1.3 Using Java for Network Programming .................................................................... 1
1.4 Java Version History ............................................................................................... 2
1.5 Java Main Components ........................................................................................... 2
1.5.1 Java Programming Language ............................................................................... 3
1.5.2 Java Platform....................................................................................................... 4
1.5.3 Application Program Interface (API) ................................................................... 5
1.6 Java Network Considerations ............................................................................................. 6
1.7 Network Programming Application......................................................................... 6
1.8 Exception ................................................................................................................ 6
1.8.1 Types of exception ................................................................................................ 7
1.8.2 Exception handling ................................................................................................ 8
1.9 Development Tool .................................................................................................. 9
1.10 Summary ................................................................................................................ 9
References ....................................................................................................................... 10
Unit 2 IP Addressing ........................................................................................................... 11
2.0 Introduction .......................................................................................................... 11
2.1 Objectives ............................................................................................................. 11
2.2 What is a Network? ............................................................................................... 11
2.3 How a Network is Connected ................................................................................ 11
2.4 OSI Model ............................................................................................................ 13

iii
2.4.1 Physical Layer ..................................................................................................... 13
2.4.2 Data Link Layer .................................................................................................. 13
2.4.3 Network Layer .................................................................................................... 14
2.4.4 Transport Layer ................................................................................................... 14
2.4.5 Session Layer ...................................................................................................... 14
2.4.6 Presentation Layer ............................................................................................... 14
2.4.7 Application Layer ................................................................................................ 14
2.5 Internet Architecture ............................................................................................. 15
2.5.1 Internet Protocol (IP) ........................................................................................... 15
2.5.2 IP Datagram Format ............................................................................................ 16
2.5.3 IP Address .......................................................................................................... 17
2.6 Domain Name System........................................................................................... 18
2.7 Internet Addressing Using Java ............................................................................. 18
2.8 Summary .............................................................................................................. 20
References ....................................................................................................................... 21
Unit 3 Data Stream.............................................................................................................. 22
3.0 Introduction .......................................................................................................... 22
3.1 Objectives ............................................................................................................. 22
3.2 Stream .................................................................................................................. 22
3.3 How do Streams Function? .................................................................................. 23
3.3.1 Input streams ....................................................................................................... 25
3.3.2 Output stream ...................................................................................................... 26
3.3.3 Filter streams ....................................................................................................... 27
3.3.4 Reader and writer ................................................................................................ 28
(a) Low level reader ..................................................................................................... 28
Example 3.3: Input Stream to Reader ........................................................................... 29
(b) Low level writers .................................................................................................... 30
3.4 Persistence and Serialisation ................................................................................. 30
3.5 Summary .............................................................................................................. 31
References ....................................................................................................................... 31
Unit 4 Threaded Application ............................................................................................... 33
4.0 Introduction .......................................................................................................... 33
4.1 Objectives ............................................................................................................. 33

iv
4.2 Thread Overview ....................................................................................................... 34
4.3 Multithreading ........................................................................................................... 35
4.3.1 Develop multithreading application using thread class ......................................... 35
4.3.2 Create multithreading application using runnable interface .................................. 36
4.4 Controlling Thread ................................................................................................ 37
4.4.1 Sleep( ) Method ................................................................................................... 37
4.4.2 Stopping thread ................................................................................................... 38
4.4.3 Suspend and resume threads ................................................................................ 39
4.4.4 CPU yield time using the Yield( ) Method............................................................ 39
4.4.5 Wait until thread end ........................................................................................... 39
4.5 Synchronisation .................................................................................................... 40
4.5.1 Method level synchronisation .............................................................................. 41
4.5.2 Preventive level synchronisation.......................................................................... 43
4.6 Communication between Threads .............................................................................. 45
4.6.1 Pipe communication ............................................................................................ 45
4.6.2 Notify thread to wait for a particular event........................................................... 45
4.7 Thread Grouping .................................................................................................. 46
4.8 Summary ................................................................................................................... 47
References ....................................................................................................................... 48
Unit 5 URL ......................................................................................................................... 49
5.0 Introduction .......................................................................................................... 49
5.1 Objectives ............................................................................................................. 49
5.2 URL Overview...................................................................................................... 49
5.3 URL and Java ............................................................................................................ 50
5.4 URL classes ............................................................................................................... 51
5.4.1 Creating a URL ................................................................................................... 51
5.4.2 Creating relative URL ......................................................................................... 51
5.4.3 Other URL builders ............................................................................................. 52
5.4.4 MalformedURLException exception ................................................................... 53
5.3.5 URL parser .......................................................................................................... 53
5.5 Reading Directly From The URL .......................................................................... 54
5.6 Connecting the URL ............................................................................................. 55
5.7 Summary .............................................................................................................. 56

v
References ....................................................................................................................... 56
Unit 6 URL Connection ...................................................................................................... 58
6.0 Introduction .......................................................................................................... 58
6.1 Objectives ............................................................................................................. 58
6.2 Overview of URLConnection .................................................................................... 58
6.3 Reading and Writing Using URLConnection ............................................................. 59
6.4 Writing Using URLConnection.................................................................................. 59
6.5 Summary .............................................................................................................. 63
References ....................................................................................................................... 64
Unit 7 HTTPURLConnection .............................................................................................. 65
7.0 Introduction .......................................................................................................... 65
7.1 Objectives ............................................................................................................. 65
7.2 Overview of HttpURLConnection ........................................................................ 65
7.3 HTTP and Java ..................................................................................................... 65
7.4 Create HttpURLConnection Object ....................................................................... 66
7.5 Using HttpURLConnection Class.......................................................................... 66
7.6 Sending Request Using HttpURLConnection ........................................................ 68
7.6.1 Sending GET request ..................................................................................... 68
7.6.2 Sending POST request ......................................................................................... 69
7.7 Summary .............................................................................................................. 70
References ....................................................................................................................... 71
Unit 8 Using Protocol Handler ............................................................................................ 72
8.0 Introduction .......................................................................................................... 72
8.1 Objectives ............................................................................................................. 72
8.2 URL Protocol Chain ............................................................................................. 72
8.3 Protocol Handler Development .................................................................................. 75
8.4 Summary .............................................................................................................. 76
References ....................................................................................................................... 77
Unit 9 Connecting to TCP Server ........................................................................................ 78
9.0 Introduction .......................................................................................................... 78
9.1 Objectives ............................................................................................................. 78
9.2 Socket ........................................................................................................................ 78
(a) Stream Socket (TCP) ............................................................................................ 78

vi
(b) Datagram Socket (UDP)........................................................................................ 78
(c) Raw Socket ........................................................................................................... 78
9.3 Communication Domain ............................................................................................ 79
9.4 Client Socket Application ..................................................................................... 80
9.5 Summary .............................................................................................................. 85
References ....................................................................................................................... 86
Unit 10 Implementing TCP Server ...................................................................................... 87
10.0 Introduction ............................................................................................................. 87
10.1 Objectives ............................................................................................................. 87
10.2 A Simple TCP/IP Server ....................................................................................... 87
10.3 Case Study Client/Server Connections using Socket/Socket Server .......................... 90
10.3 Multithreaded Server ............................................................................................... 92
10.5 Summary .............................................................................................................. 94
References ....................................................................................................................... 95

vii
Table of Figures
Figure 1.1: Main features of Java Language .......................................................................... 3
Figure 1.2: Exception class category ..................................................................................... 7
Figure 2.1: Abstract visual of a network .............................................................................. 12
Figure 2.2: Resemblance of an information packet .............................................................. 12
Figure 2.3 : Layers of OSI model ........................................................................................ 13
Figure 2.4: Network architecture based on the OSI Model ................................................... 14
Figure 2.5: IP network support among the physical networks .............................................. 16
Figure 2.6: Ipv4 model ........................................................................................................ 16
Figure 2.7: Ipv4 classes ....................................................................................................... 18
Figure 3.1: Sub-categories of streams .................................................................................. 23
Figure 3.2: Sub-categories of streams .................................................................................. 23
Figure 3.3: Byte stream family ............................................................................................ 24
Figure 3.4: Character streams family ................................................................................... 24
Figure 4.1: Application process that manages more than one subprocess ............................. 35
Figure 4.2: Synchronisation mechanisms............................................................................. 41
Figure 4.3: Simultaneous access to counter class ................................................................. 41
Figure 4.4: Safe threads being accessed from threads class method ..................................... 42
Figure 4.5: Thread grouping ................................................................................................ 46
Figure 5.1: URL used by Sun Microsystems........................................................................ 49
Figure 5.2: The URL schematics ......................................................................................... 50
Figure 6.1: Output and input stream process ........................................................................ 62
Figure 8.1: URL protocol chain ........................................................................................... 73
Figure 8.2: URL content type sequence ............................................................................... 74
Figure 9.1: An abstract view of communication between the web server and the host .......... 79
Figure 9.2: Abstract view of a socket communication.......................................................... 79
Figure 9.3: HyperTerminal Private Edition .......................................................................... 80
Figure 9.4: Connect to Dialog ............................................................................................. 81
Figure 9.5: Telnet’s Command Prompt Output .................................................................... 81
Figure 9.6: HyperTerminal’s Output ................................................................................... 82
Figure 9.7: The output from OUM website .......................................................................... 83
Figure 10.1: Using TELNET to connect to the Server.......................................................... 89
Figure 10.2: Connection terminates when the ENTER key is pressed .................................. 89
Figure 10.3: Connecting to the Server with the HyperTerminal ........................................... 90
Figure 10.4: Disconnected message appears when ENTER is pressed ................................. 90
Figure 10.5:Server Program Output ..................................................................................... 92

viii
BLANK PAGE
Module Overview
Harnessing the power of networks is undoubtedly the most essential skill for today’s software
developers. Applications created today whatever their intended scope or audience, will almost
certainly run on machines linked by a global network of computing resources. The Network
Programming course (BITH261) will introduce the network programming using Java
programming language. The course is offered by the Faculty of Information Technology and
Multimedia Communication, Zimbabwe Open University (ZOU).

Course Objectives
The Network Programming course is a discipline in networking based on the client-server
network and the distributed system using Java programming language.

You will be exposed to the Open Systems Interconnection (OSI) model, Transmission Control
Protocol (TCP), client-server concepts and the application of streams. Upon completion of this
course you will have the knowledge of the OSI and Transmission Control Protocol/Internet
Protocol (TCP/IP) model and its communication, and have the skills required in writing a
network application based on the TCP/IP model. It is highly recommended that each unit
should be thoroughly understood before proceeding to the subsequent units.

The primary objective of this course is to develop your skills in network application and the
utilisation of Object Oriented Programming in developing them.

At the end of this course, you should be able to;

• understand Java programming language in the network programming context


• learn the easiest approach to use Java classes to access information on the WWW
• write a client-server application using the TCP and UDP protocol; and
• develop a server that applies the multithreaded concept

Course Synopsis
This course is divided into ten units. The following are the synopses for each unit:

Unit 1: Introduction to Java Language


This unit is on the history, the design objective and the Java programming language in general
that is associated with networking. Discussions will be focused on byte codes formed by the
Java compiler and its interpretation by the JVM (Java Virtual Machine). A few Java APIs’
(Application Programming Interface) that operate on the network will be explained. In certain
situations, decisions on network, safety and exceptional handling are needed for Java
programming. Finally, a few practical Java applications will be discussed.

Unit 2: IP Addressing
This unit is an introduction to the network concepts and its communication with other networks.
The OSI model and its layers, the architecture of the Internet Protocol, and domain names will

ix
be explained. You will also be exposed to the java class (java.InetAddress) which is used in
network applications.

Unit 3: Data Stream


In this unit we discuss the importance of streamed communication in the java network
application which is essential when communicating with TCP based networks. The functions
of streams will be explained. You will also study inherited classes and methods in the java
input and output (java.io) package to be applied when reading and writing streams into the two
main classes of streams, byte stream and character stream.

Unit 4: Threaded Application


This unit focuses on multithreading. You will learn the concepts, applications, communication
and synchronisation that involve threads and also grouping of threads. The understanding of
thread and multithread is important before developing thread application by extending
java.Lang.Thread and implementing java.lang.runnable. Threads created in the program can be
controlled using control methods available in Java. The concept of threads will be widely used
in later units.

Unit 5: Uniform Resource Locator (URL)


In this unit we talk about accessing data from the Internet using URL. You will be exposed to
URL concept and how information sharing is done using the URL class. Thorough
understanding of this unit will ease programming tasks using the URL class like creating,
connecting and reading information from the Internet.

Unit 6: URL Connection


In this unit we discuss the basic concepts of URLconnection class. You will be exposed to
URLconnection class functions and implementation in the java programming language. By the
end of this unit, you should have acquired the skills of creating, reading, and writing
information from the client server using the URLconnection class and string queries using the
GET and POST method.

Unit 7: HTTPURLConnection
In this unit we examine the URL subclass HttpURLconnection, which is used solely for
Hypertext Transfer Protocol (HTTP). You will be exposed to writing programs using the
HttpURLconnection class, which is creating, reading and writing of information from the client
to server. You will also learn the connecting techniques using GET and POST methods.

Unit 8: Using Protocol Handler


In this unit we introduce the protocol handler. We will also explain the protocol chain concept
in java. The protocol handler supports protocols that are not supported by the URL class. We
will also let you know how to add a standard protocol in the Java class through protocol chains.

Unit 9: Connecting to TCP Server


In the unit we discuss the basic concept of TCP socket and its function. To fully understand the
socket class functions, you will be exposed to the Telnet application or hyperterminal in
Windows or Unix. You will be taught reading and writing of data from and to streams. Finally,
you are expected to create a client application to retrieve information from a server.

x
Unit 10: Implementing TCP Server
In unit 10 we talk about data transportation by using TCP. This protocol is widely used in the
Internet. It uses data streams to communicate. In this unit we expose you to ServerSocket in
network programming and the use of Telnet application or hyperterminal to test a newly
developed server. You will also be taught using ServerSocket class to read and write data from
streams and create server application using TCP.

General Knowledge
Knowledge of Object Oriented Programming is needed before registering for this course.

Reference Material
Primary References

Elliote. H. (2000). Java Network Programming. United States: O’Reilly.

Additional References

David. R.& Michael. R (2002). Java Network Programming and Distributed Computing.
Boston: Addison Wesley.

Merlin. H et al. (1999). Java Network Programming. Greenwich: Manning.

xi
BLANK PAGE
Unit 1 Introduction to Java Language

1.0 Introduction
In this unit we discuss the Java language and its application in network programming. Although
you have taken an Object Oriented Programming course, however, this discussion on Java, its
components, main features and programming interface is necessary to paint a clearer picture of
Java language and helps you develop network applications. This unit focuses more on
introducing the Java language. In the following units we will discuss in detail the use of this
language in network applications.

1.1 Objectives
At the end of this unit, you should able to:

• identify five network applications developed using Java programming language


• examine the history and evolution of Java programming language and the purpose and
its importance
• describe the three main components of Java and its features
• identify networking packages from Java API
• explain networking considerations using Java language
• discuss exception handling and two categories of exception class provided by Java
programming language
• analyse the tools used in developing Java application;

1.2 Java Background


There are four generations of programming language. There are various types of programming
language developed by various organisations in each generation. Java programming language
is the fourth generation language and it is object oriented such as C++ and Smalltalk. This
language was developed in the early 90s with the purpose of communicating consumer
electronic devices for residential. It was known as Oak. In 1995/96, its name was changed to
Java after it was introduced as programming language for networking.

Java programming language became popular in networking world in a very short period of time
because of its flexibility. We can write and compile Java programs in platform such as
Windows. However, this program can also be used on machines like Macintosh, Unix, Linux
or Windows NT without changing the program code. This helps programmers to develop
application for different operating system easily.

1.3 Using Java for Network Programming


Java programming language is used in network programming application because:
• Java has a comprehensive and complete class library.
• Java is able to handle many low-level network problems that are difficult to overcome
by using C programming language.
• Network is the core of Java programming.

1
1.4 Java Version History

There are many java versions that have been released. Current stable release of Java is Java
SE 8 (Nagar. M 2010).

1. JDK Alpha and Beta (1995)


2. JDK 1.0 (23rd Jan, 1996)
3. JDK 1.1 (19th Feb, 1997)
4. J2SE 1.2 (8th Dec, 1998)
5. J2SE 1.3 (8th May, 2000)
6. J2SE 1.4 (6th Feb, 2002)
7. J2SE 5.0 (30th Sep, 2004)
8. Java SE 6 (11th Dec, 2006)
9. Java SE 7 (28th July, 2011)
10. Java SE 8 (18th March, 2014)

Website
You must be very familiar with Java programming language by now. However, do you know
the history and development of Java since its creation, 23 May 1995 until today?

For more information on the history and development of Java, you can browse through
http://java.sun.com/java2/whatis/. The facts from this website can help you to answer the
questions below.

Activity 1.1
Answer questions above to test your understanding.

1. Give a brief history of Java programming language.


2. State the differences and similarities between JAVA and C++.

1.5 Java Main Components


In this section we discuss the main Java components. Each component is equally important
and you need to understand them very well. Java components are as shown in Table 1.1.

Table 1.1: Java Components

Based on Table 1.1, Java has three components that are interrelated. Therefore, you need to
clearly understand each of these components.

2
1.5.1 Java Programming Language
Java programming language is designed to handle challenges that arise when developing
distributed and heterogeneous network applications. The main challenges are:
• To guarantee application production using minimum system resources
• Can be implemented on any device and software platform
• Dynamically expandable

Figure 1.1: Main features of Java Language

Below are explanations for the main features of Java Language:


(a) Object Oriented
Java programming language uses the latest programming approach of bottom-up object
oriented technique. The programmers can access to object library that contains tested classes
and offer functions from basic data types to graphic interface, networking and so on. Java
libraries are expandable to support new actions.
(b) Easy
Java language still uses simple basic programming approach. Java approach is the same as
object oriented programming such as C++.
Advantage of Java is that it has removed a few complex features which are difficult to
understand in C++. The users that use C++ programming language can easily switch to Java
language since it uses a similar object oriented concept.
(c) Automatic Garbage Collection
When an object is created, memory space will be allocated to store its attribute variables. Since
the memory space is limited, the space that is no longer in use known as “garbage” needs to be
released for other objects’ use. In this case, Java provides a garbage collector to execute a
garbage collection process and release the garbage when free spaces are not sufficient.
(d) Portable
Programming language is called portable if it is not dependent on computer architecture. Java
technology improves the portable features by strengthening the basic language definition. It
fixes the size of basic data types and their arithmetic actions. As an example, size of int data in
Intel Pentium machine is the same as in Scalable Processor Architecture (SPARC) machine.
(e) Security

3
Since Java provides distributed application, security is an important issue to be taken into
consideration. Java application is safe from unauthorised codes because of its reliable security.
It protects Java application from runtimestacks overflow, memory space corruption and many
more.

(f) High Reliability


Java is also dependable because application written using this language has a high level of
reliability. It provides time compilation checking facilities and runtime checking.

(g) High Performance


Applications written with Java are high in performance with Just-in-Time (JIT) Compiler.

(h) Multithreaded
Java is Internet “enable” and it supports multithreading that executes many tasks at a time.

Generally, application development using Java Programming Language is more dynamic than
other programming language base on its support and Java’s responsiveness to current issues.

Your Idea
Before proceeding to the next unit, try to recall and list down:
(a) Java main components
(b) Java main features
You can sketch the Java main components and features to help you to remember the
important points.

1.5.2 Java Platform


Java language is the most important part of Java technology. The written source codes need to
be compiled in order for a computer to understand the instructions in the codes. The compiled
codes can be run using Java platform. The application that is written using Java language needs
a platform to run on.

Java platform that base on JVM (Java Virtual Machine) can run Java application on any CPU
(Central Processing Unit) architecture. JVM is available in JRE (Java Runtime Environment).
The synopses about JVM and JRE are as below:

JVM
• It is a hardware device emulation.
• Emulation is a process of copying and adapting an object.
• JVM is produced during a program compilation on a computer according to the
computer architecture.

JRE
• Provides libraries which contain Java API classes.
• JVM is a part of JRE.
• Nowadays, there are various JRE which support current requirements.

JRE categories as shown in Table 1.2.

4
Table 1.2: Java Categories

1.5.3 Application Program Interface (API)


API is another important component in technology Java because it provides classes and
components that allow Java to perform tasks as listed below:
• Read and write files in hard disks.
• Produce GUI with menus, buttons and texts.
• Draw pictures using functions such as lines, circles, boxes and oval shapes.
• Access network resources.
• Store data using data structure and linked list.
• Manipulate and process data like text, number and image.
• Access information from database.
• Change information records.
API provides various functions in Java. Nowadays, there are many packages provided by
Java. Some of the main packages for network application are listed in Table 1.3.

Table 1.3: Java API Package

5
Activity1.2
Answer questions below to test your understanding.
1. What do you understand about Java main features? Explain.
2. List down classes available in java.net and servlet.

1.6 Java Network Considerations


Although Java is suitable for writing network applications, there are a few matters that you
need to pay attention to when using this language for networking purposes.

Java does not provide low-level access to internet protocols because Java application is not
written on physical layer. Apart from that, Java also stresses on high security aspects on applets.
This is done by not allowing applet to attach itself to any local port. This technique will be able
to stop Applet from disguising as an authentic service and reach internal server. However,
digital signature can be used to allow access.

Activity1.3
Answer questions below to test your understanding.
1. State the reasons why Java does not support low level access.
2. Why are considerations necessary in Java?

1.7 Network Programming Application


Network programming allows developed applications to be connected to machine from all over
the world without boundary. With networking, applications can share existing external
resources. Examples of network application are listed in Table 1.4:

Table 1.4: Network Applications

1.8 Exception
Exception handling is a mechanism to handle problems or errors that occur during run time.
There will be high chances for error occurrence during run time, although there are no errors
during compilation. It happens when there are certain restraints during runtime. For example,
when a source code accesses a file which does not exist, the application will not proceed.

6
Basically, exception is an abnormal situation which occurs during application runtime.
Exception is presented as an object which contains variables to trace errors and enables it to
analyse source of problem or gives clues as to why it happened.

When exceptions occur, methods will throw exceptions and submit them to caller method. The
caller method will catch exception or throw them to caller method. Caller method needs to
catch exception and prepares an exception handling or show type of exception it throws.
Without exception handling, there will be tendency for errors to occur during runtime.

1.8.1 Types of exception


There are many types of exception in Java technology. However, all exceptions share the same
inheritance class from java.lang.Throwable.

Exception is divided into two categories as shown in Figure 1.2.

Figure 1.2: Exception class category

Exception from Error class is generated by serious error that could not handled by Java and
out of software developer’s control. Examples of Error class are as shown in Table 1.5.

Table 1.5: Types of Exception Error

Exception from Exception class usually deals with calling method. This exception also comes
from serious errors which are difficult to overcome. The programmer is able to create exception
handling code although the compiler does not provide them. Examples of exception in this
category are listed in Table 1.6.

7
Table 1.6: Exception Classes

Exception management involves catching and throwing exception to calling method. There are
many exceptions and each of these exceptions has their own subclasses. As an example, when
dealing with TCP socket, SocketException might be thrown. This class has a few subclasses
such as ConnectException that will be thrown or NoRouteToHost that indicates disconnected
network connection or blocked by firewall.

1.8.2 Exception handling


Java technology provides facility to programmers in exception handling by writing exception
handling in programs. The reasons for exception are as below:

• When network connection to Internet was disconnected or traffic is congested.


• The user resides behind the firewall.
• Security obstacle.

Java provides three types of statements for exception handling, such as:

• try statement
• catch statement
• finally statement

Therefore, three blocks are created in a program to handle exception. However, creation of
finally block depends on the programmer’s requirement.

// try block that generates exception

try {
// generates exception
}
catch {
//handles exception
}
finally {
// Release the thrown exception
// after try block
}

8
It is important for you to know and understand the ways on handling exception to overcome
errors during runtime.

Activity 1.4
Answer questions below to test your understanding.
1. Give an example of software agent. Why is it called network application?
2. What do you understand about exception handling and explain the reasons for
exception?

1.9 Development Tool


Nowadays, there are many application development tools and Java programming language
software. Below are a few tools that allow Java software to be edited, compiled and debugged.

(i) Integrated Development Environments (IDE). Below are a few IDEpackages available in
development tools:
• Borland Jbuilder
• Symantec Visual Cafe
• Visual Age for Java
• Visual J++
• Forte for Java Community Edition
(ii) Java Developments Kits.

Your Idea
After learning about Java and its advantages, list down a few drawbacks of C++ compared to
Java programming. Why is Java suitable for network programming compared to C++?

Activity 1.5
Answer questions below to test your understanding.

Is it true that application written in Visual J++ can be run in other Integrated Development
Environment (IDE)? Please state reasonable reasons.

1.10 Summary
In this unit we hope you gained deeper understandings on Java components as not only a
programming language and software platform, but also rich with computer language and
software executable environment that is completed with API class library features that supports
network.

Overall, in this unit we discussed Java on network environment. You learnt about Java
applications on network, Java issues, API packages and also Java application development
tools.

In conclusion, this unit gave you Java knowledge on network environment and the related
issues with network implementation using Java.

9
References
Puntambekar A.A (2008), Internet Programming, First Edition, Technical Publications Pune

Niemeyer P and Leuck D (2013), Learning Java, Fourth Edition, O’REILLY

Nagar.M (2010), History of Java, Available from: < http://www.javatpoint.com/history-of-


java.> [18 December 2014]

Free java guide & tutorials (2013), History of java programming language, Available from
<http://www.freejavaguide.com/history.html> [18 December 2014]

10
Unit 2 IP Addressing

2.0 Introduction
In this unit we discuss basic network concepts and a few important units regarding network
theory. If you have basic knowledge of the network background, in this unit we focus on
implementation of network programming using Java. Knowledge from this unit will be the
foundation for the subsequent units.

2.1 Objectives
At the end of this unit, you should be able to:
• explain network concepts
• examine interconnection between network
• describe the internet architecture
• discuss internet protocol
• explain IP datagram format
• explain IP addresses and domain name
• write an application to get IP and domain name using InetAddress
2.2 What is a Network?
What do you understand about a network? When and where is it used?

Some people think that network is a collection of computers which are connected to each other.
However, this opinion is incomplete because network is not only restricted to computers but
also involve collection of hardware that shares a communication protocol and medium like
network cables, dial-up connection and wireless connection.

2.3 How a Network is connected


Do you know how a computer operates?

It is important to have a system to manage data sending in a network with many computers, so
that sent data can be received by the authorised recipient.

How can this be implemented?

After familiarising yourself with networks, you need to know how hardware in a network is
connected to each other. Network connection involves physical connection; data addressing
and sending are done using packets.

11
Figure 2.1: Abstract visual of a network

A few tools are needed to create a physical connection. Some of these tools are as listed below:

• Network card
• Switch
• Router
• Hub
• Network cable
• Gateway
After a particular hardware called node is installed, an IP address will be generated and
assigned to it. Each hardware in a network has a unique IP address. Once the physical
connection is created and each node is provided with a unique address, information can be
transferred between nodes that are interconnected in a network.
Information that needs to be sent will be broken into a few smaller units which are called
packets. This is done to avoid network congestion and improve effectiveness in information
transmission. Figure 2.2 shows example of an information packet.

Figure 2.2: Resemblance of an information packet

12
The information that is broken into packets have header which are identified as packet address.
When the packets are received by a recipient, it will be reassembled to form the original
information. Therefore, the packets only exist during delivery process.

2.4 OSI Model


It is like communicating using different languages in a network that has many types of
hardware. Therefore, there must be a standard system which ensures the smoothness in
communication flow. How does this standard system operate?
Open system interconnection is a model that was introduced to enable hardware with a different
system to communicate with each other. It was introduced by International Standard
Organisation (ISO). OSI model has seven layers as shown in Figure 2.3.

Figure 2.3 : Layers of OSI model

2.4.1 Physical Layer


This is a basic layer in network communication. In this layer, network hardware sends
series of bits between two nodes. It transmits data over a bit stream from one hop to the
next and provides electrical and mechanical specification. The Java programmers do not
write application in this layer.

2.4.2 Data Link Layer


This layer is responsible for preparing better data transmission and gathering data in frames.
Frame is similar to packet, but it only carries single type data and is very specific to a
particular hardware. However, data packet is high level whereby it allows data transmission
between different types of networks. Weakness of this data link layer is it does not
guarantee resending of damaged frames.

13
2.4.3 Network Layer
The network layer deals with data packets and frames. This layer also introduces some
important network concepts like network addressing and routing. Level of communication
in this layer is categorised as low level. Therefore, a programmer needs to write service
software for this layer.

2.4.4 Transport Layer


This layer explains how the data is being transferred. Apart from that, it also handles a few
issues like automatic error detection and correction, and data flow control to limit
maximum number of data that can be transferred at a time so that network congestion can
be prevented.

2.4.5 Session Layer


This layer provides data exchange facilities from one application to another. It also creates
or terminates network communication session. Session management involves many tasks
like creating, synchronisation and re-connecting the terminated session.

2.4.6 Presentation Layer


Each machine uses different data types because these systems are based on the 8 bit, 16 bit
or 32 bit system. Therefore, this layer changes data format into different formats which
suits the other node system.

2.4.7 Application Layer


This provides the users access to network resources. Many applications are written by the
programmers in this layer. There are a few application layer protocols. Some of them are
to identify related semantics on how the requests are being made such as requesting for file
or checking e-mails. In Java, most of the applications are written in this layer.

Figure 2.4: Network architecture based on the OSI Model

14
Activity 2.1
Answer questions below to test your understanding.
1. How many layers are there in TCP model? Draw the layers.
2. Explain the functions of each of the TCP model layers that you have drawn in
Question 1.
3. Describe the differences between OSI model and TCP model.
4. Explain the concept of layered task.
5. What is the OSI model? Explain its layers and their responsibilities.
6. Analyse how the communication takes place between layers of OSI model.

2.5 Internet Architecture


Internet is the biggest computer network. The data delivered through network needs to have a
destination which has a unique address. Do you know this address format?
Internet is the biggest IP based network in the world. It consists of groups of computers from
all over the world. Internet was created from ARPANET project. Nowadays, Internet is an open
system that is developed on network layers, the transportation and application protocol layers.
Internet is amazing because of its flexibility between various type of computer, hardware and
operating system.
Today’s internet is the output of innovations and experiments that have been carried out for
about a decade since its founding. The protocol involves TCP/IP which has been designed,
tested and improved from time to time. Important features of TCP/IP are:

• Allows resource sharing between networks


• Enables various hardware and software to operate with any CPU architecture, operating
system and network card
• Reliable and secure
• Easy and effective protocol
History of Internet is one of the most interesting units to read. If you are interested to know
more about history of Internet and its development, you can browse through
http://www.isoc.org/internet/history/

2.5.1 Internet Protocol (IP)


Internet Protocol (IP) on the network layer is used for sending data packets over the Internet.
It is also known as a protocol for packet-switched networks. Information exchanged between
two host using IP packets is referred to as IP datagram. The purpose of IP datagram usage is to
enable data transmission though various type of networks.

15
Figure 2.5: IP network support among the physical networks

2.5.2 IP Datagram Format


IP datagram carries important information to control data transmission. This information is
kept on the head of datagram and followed by the real data. Basic knowledge on how an IP
datagram operates is sufficient for readers to understand how the Internet communicates.
Today, IP version in use is IPv4. The IP model IPv4 is divided into four parts as shown in
Figure 2.6.

Figure 2.6: IPv4 model

16
On IPv4, there are a little more than four billion possible IP addresses, not even one for every
person on the planet and much less for every computer. A transition is underway to IPv6
which uses 16 byte addresses. This provides enough IP addresses to every computer. Earlier
versions of java from java 1.3 backwards do not support IPv6.

Activity 2.2
Answer questions below to test your understanding.
1. Based on the IPv4 model, describe all the parts and usage of each part in the IPv4 model
structure.
2. Describe the structure of IPv6 model.

2.5.3 IP Address
IP address is a numeric base Internet address to provide facilities to access the Internet. Each
computer that connects to Internet has a unique number that helps to identify the computer
easily. A computer cannot be accessed from the internet if it does not own an IP address.
Size of IP address is 4 bytes (32 bits) that usually stated in dotted decimal notation, for an
example 192.168.0.7. Each machine can have one IP address. However, this machine can be
installed with many network cards and uses more IP address.
Do you know that you can identify IP configuration in your computer?
If your computer is using Windows 2000/XP/NT/7:

• Click Start button


• Click Run and type cmd on the text box then click OK.
• Type ipconfig/all on the command window and press Enter button.
Command window will list down all information about IP configuration and information on
your computer network. For more information about IP address, please look it up at
www.google.com
There are five different structures of IP addresses. The purpose of IP address being categorised
into classes with different numbers of Host ID is because each private network needs an IP
address block for itself. However, allocation of IP blocks that are extremely big can lead to
wastage of address space. Therefore, blocks for private network IP address size are based on
the number of hosts.
Refer to Figure 2.7

• Class A has 128 addresses as Net ID and 16,777,216 addresses as Host ID


• Class B has 16,384 addresses as Net ID and 65,536 addresses as Host ID
• Class C has 2,097,152 addresses as Net ID and 256 addresses as Host ID

17
Figure 2.7: IPv4 classes

Class A is for class that has a small network ID but has a big Host ID. With that, private
networks can have many machines since they have many Host IDs. Networks that use Class B
and C IP addressing have less number of hosts compared to Class A. Class D and E do not
have any network ID because Class D is used to send data streams to a group of concurrent
receivers. It can reduce the required bandwidth to support services that are used by many
people. Class E is defined as a reserved class that has never been used.

2.6 Domain Name System


What is the name of organisation that manages top level domain (TLD) in Zimbabwe?
IP addressing has an efficient system to manage the network called Domain Name System
(DNS). DNS makes the Internet user-friendly by providing names in text format for each IP
address. Any entity from trading, Government, Education or Private sectors can apply for DNS.
Domain name is the name of a host on the Internet. Domain Name System (DNS) translates
the domain name to an IP address so that the router can send messages to the actual host.
DNS is divided into a few structural levels based on the type of address such as .net, .com, .org,
.gov, .edu and others.

Activity 2.3
Answer questions below to test your understanding.
Today, IPv6 model has been introduced, explain the structure of IPv6 and the improvements
that have been done to this model.

2.7 Internet Addressing Using Java


When a communication occurs between computers, how can we ensure that the communication
occurs between the appropriate computers?
Internet addressing is performed by using Java on java.net.InetAddress class. This class can
perform many tasks such as getting the IP address from the host name and others. This class
does not have a public constructor, but it has two static methods that return InetAddress object.

18
When an IP address cannot be accessed, it may be due to an interruption in the network
connection or the connection behind the proxy. This can cause UnknownHostException error
to be thrown to body of program. Below is an example on how the static method in
InetAddress class is used.
To get local host address we need to create InetAddress variable, as shown below:
try{
InetAddress localadd = InetAddress.getLocalHost( );
}catch (UnknownHostException e){}
IP address can be displayed by calling localadd that has been created, above that is:
System.out.println(“IP Address”+localadd.getHostAddress));
IP address and host name for other users can be obtained by creating InetAddress class variable,
that is:
try{
String nama_host;
InetAddress address =InetAddress.getByName(nama_host);
}catch UnknownHostException e){}
Displaying IP address is by calling the address variable above and followed by
getHostAddress( ) method as below:
System.out.println(“IP Address”+address.getHostAddress( ));
And displaying host name is done by calling getHostName( ) method as below:
System.out.println(“Host Name” +address.getHostName( ));
Implementation of InetAddress class is easy and you with need knowledge to be able to use
this class and its methods. In the following units, you will be exposed to network applications
and techniques to write those applications.

Activity 2.4
Answer questions below to test your understanding.
1. Write a program that can display local IP.
2. Write a program that can display 32 bit IP address and user domain name in the WAN
network.

19
2.8 Summary
Knowledge and understanding of network theories is very important for you. Network theories
give you knowledge on how the machines are interconnected and most importantly are the OSI
layers which are useful in writing network application using Java.
Apart from physical connections and OSI model, Internet architecture is highlighted in this unit
because Internet architecture contains IP addressing for each connected machine. You need to
learn IP address and its architectures, IP datagram format and domain name.
Finally, you have been exposed to writing of Java programs to obtain IP addresses and domain
names from local and interconnected machines on the network.

20
References
Alani. M (2014), Guide to OSI and TCP/IP Models, SpringerBriefs in Computer
Science

Behrouz.A. F (2007), Data Communication & Networking, Fourth Edition, McGraw-


Hill

Domain Name System, Available from: www.cs.virginia.edu/~cs458/slides/module19-


dnsv2.pdf [12 December 2014]

Goerzen .J (2004), Foundations of Python Network Programming, Apress

Graba.J (2013), an Introduction to Network Programming with Java-Java 7


Compatible, Third Edition, Springer

IP Addressing, Available from: http://www.cs.virginia.edu/~cs458/slides/module03-


ipaddrV2.pdf [ 12 December 2014]

21
BLANK PAGE
Unit 3 Data Stream

3.0 Introduction
Every computer receives input and produces output after a process. Developing an input and
output system is a challenging task for any programmer. There are many ways of dealing with
input and output. Java assists programmers by providing a variety of classes from basic input
and output to classes that are more complex. Java not only covers input communication, filing
output and network connection but also has many methods such as serial, random, binary,
character, line and alphabets.
The knowledge of input and output stream is essential to any programmer associated with
network application development.

3.1 Objectives
At the end of this unit, you should be able to:

• explain the concept and functionality of streams


• describe two stream types and their stream family
• write a program by using input and output stream
• explain filter stream and identify the types
• discuss Reader and Writer and write a program related to it
• evaluate the concept of Persistence and Serialization

3.2 Stream
Data transfers via the network cannot be done simultaneously. How then is data sent and
received?
Most Java applications apply stream approach in data sharing and communication. This
approach is used when communicating between network and file as well as between network
and application. Stream concept is essential when dealing with network application except
UDP communication. UDP will be discussed in Unit 3. Hence, network programmers need to
familiarise themselves with stream concept to ensure a well written network application.
Byte level communication is performed by Java using data stream because data is sent and
received in byte format. Data is communicated similarly as how water pipes distribute water to
our houses.
Water distribution is done by using pipes to connect the main source to destinations. Water will
flow and reach the destination if the pipe installation and connection is done correctly.
Similarly, the distribution and flow of data depends on the selection of appropriate streams in
Java.
Selection of appropriate streams depends on the type of data transferred and how the data will
be used. Streams are adaptable according to various factors and is easily managed to suit
various interfaces. Besides that, streams in Java are considered flexible since it has no
limitation on the stream size sent. At the moment, there are 2 streams categories namely input
stream and output stream as seen in Figure 3.1.

22
Figure 3.1: Sub-categories of streams

Data transferred in byte series is the core of network programming. The streaming approach is
a standard interface for data transfer regardless of the data type being transferred and received
or the mechanisms used to transfer the data via the network.
Stream is not only limited to data transferring through network but can also be used when
writing data structures, files or any other applications. However, there are many ways to
transfer data to network, and stream I/O provides a consistent interface for network
communication.

3.3 How do Streams Function?


The java.io package provides classes of network communication using streams. Stream is
divided into 2, namely input stream and output stream. In addition, stream I/O is categorised
into 2 sub-categories, as seen in Figure 3.2

Figure 3.2: Sub-categories of streams

Byte stream is 8 bit in size whereas the character stream is 16 bit. The byte
Stream, has a set of sub-classes with different capability which are:
• Object
• Filters
• Data BufferedLineNumber
• Print

The byte stream family is as seen in Figure 3.3.

23
Figure 3.3: Byte stream family

The 16 bit character stream consists of reader and writer. The character stream family is shown
in Figure 3.4.

Figure 3.4: Character streams family


After understanding streams, think about the relationship between streams and networks. How
are streams linked to networks?

24
3.3.1 Input streams
Input stream from the java.io package and low level stream is usually the immediate choice in
performing the tasks. Figure 3.3 shows input streams is divided into 2 sub-classes namely
FileInputStream and FilterInputStream. Creating low level streams as in Table 3.1, makes
reading of data from data source possible. Input stream acts as the information user that breaks-
down the data as it is read. At this moment, the data cannot be read again or deleted but
transferred to the next information byte.

Table 3.1 : Low Input Stream from The java.io Package

Example 3.1: Reading Files Using the FileInputStream Method


import java.io.*;
class FileInputStreamDemo {
public static void main(String args[ ]) throws Exception {
InputStream fileInput = new
FileInputStream("FileInputStreamDemo.java");
int data = fileInput.read( );
while( data != -1) {
System.out.write(data);
data = fileInput.read( );
}
fileInput.close( );
}
}

25
Example 3.1 shows a program reading an input using InputStream class. The explanation for
the program Example 3.1 is as the following:
(a) Creating Input Stream and Reading from a Specific File

InputStream fileInput = new


FileInputStream("FileInputStreamDemo.java");

(b) Reading the First Data Byte

int data = fileInput.read( );


(c) If There are More Data

• Send Data to Standard Output

System.out.write(data);

• Read the Next Byte

data = fileInput.read( );

(d) Close

fileInput.close( );

3.3.2 Output stream


The java.io.outputStream is an abstract class inherited from all the output streams, whether low
level streams or filter streams. Output streams differ from input streams because input streams
functions as users, whereas output streams creates information bytes and transfers it. In Table
3.2, there are 6 low level output streams that are important. Just like input stream, data
communicates in series using the FIFO approach. Data is transferred in bytes at one time or
part of an array byte. If bytes are read all at one time, the system's performance will be affected.

Table 3.2 Low Level Output Streams from the java.io package

The program in example 3.2 shows how low level output streams is used. You will need to
understand the steps of read and write of output streams given below.

26
Example 3.2: Reading and Writing Files Using FileOutputStream
import java.io.*;
class FileOutputStreamDemo {
public static void main(String args[]) throws Exception {
String source = "Now is the time for all good men\n“ + " to come to the aid of
their country\n" + " and pay their due taxes.";
byte buf[] = source.getBytes( );
OutputStream f0 = new FileOutputStream("file1.txt");
for (int i=0; i < buf.length; i += 2) {
f0.write(buf[i]);
}
f0.close( );
OutputStream f1 = new FileOutputStream("file2.txt");
f1.write(buf); f1.close( );
}
}

The explanation for Example 3.2 is as the following:


(a) Create Output Stream

OutputStream f0 = new FileOutputStream("file1.txt");

(b) Read Data Bytes to Fle

f0.write(buf[i]);

(c) Read the Next Byte

f0.write(buf[i]);

(d) Write to File

f1.write(buf);

(e) Close

f1.close( );

3.3.3 Filter streams


Filter streams are used to overcome the limitations of the low level streams that can be
inefficient and not flexible. The filter stream adds functionality to stream or method available
by allowing access through a different way.

Filter makes it easier for programmer in writing application because they can use strings, text
lines and numbers. Apart from that, it can be connected to low level streams and has better
buffering capabilities. Following shows how to connect filter stream output.

27
FileOutputStream fout = new FileOutputStream(somefile);
PrintStream pout = new PrintStream(fout);
pout.println(“hello world”);

Table 3.3 shows the types of input and output filter streams.

Table 3.3: Input and Output Filter Streams

3.3.4 Reader and writer


JDK from version 1.1 supports Unicode character which is the best alternative to writing texts.
Unicode is an extension to normal character set. The size of a normal character is 8 bit while
Unicode is 16 bit which allows 65,536 characters.

(a) Low level reader


Just like input stream, there are many types of low level readers that communicate with data
source like files or data structures, and there are filter reader for high level communication.
Table 3.4 shows low level readers available in the java.io package.

Table 3.4: Low Level Reader Streams from the java.io Package

28
Example 3.3: Input Stream to Reader
import java.io*;
class ReaderDemo {
public static void main (String []args) throws Exception {
//create an input stream reader and a buffered reader to be able
// to read in input from the key board.
InputStream input = System.in;
InputStreamReader reader = new InputStreamReader(input);
BufferedReader bufReader = new BufferedReader(reader);
//ask the user for the name
System.out.println(“What is your name?”);
//read the user’s name in from the keyboard
String s = bufReader.readLine( );
//display name
System.out.println(“Your name is:” + s);
}
}

These are the steps from input stream to reader:


(i) Get the Input Stream that Represents the Standard Input

InputStream input=System.in;

(ii) Create InputStreamReader

InputStreamReader reader= new InputStreamReader(input);

(iii) Connect to BufferedReader

BufferedReader bufReader = new BufferedReader(reader);


(iv) Use readLine( ) Method

String s = bufReader.readLine( );

Apart from low level readers, the java.io package also consists of filter readers which allow
functionality to new methods or processing data via buffers. It is from the java.io.FilterReader
class. Filters will always communicate with other readers and allows interchanging between
one another. Table 3.5 shows filters available in java.io package.

Table 3.5: Filter Readers from the java.io Package

29
(b) Low level writers
There are many types of low level writers and a few share similarities with OutputStream while
the rest are new classes that were created to handle output like character array. Table 3.6 shows
low level writers found in the java.io package.

Table 3.6: Low Level Writer Classes from the java.io Package

Each writer class has methods and constructors.

Steps from output stream to writer


(i) Get the output stream and assign it to the standard output.
(ii) Create the OutputStreamWriter.
(iii) Write data to the standard output via the writer created by the OutputStreamWriter.
(iv) Flush and close the writer.
Like reader, writer too has filter that act as a filter by connecting available writer streams and
provides different functionalities. Take note that filter writer does not have sub-classes. Table
3.7 shows a few filter writers:

Table 3.7: Low Level Filter Writer Classes from the java.io Package

Activity 3.1
To test your comprehension, try answering this question.
Based on the steps of output stream to writer, write a program by following each step.

3.4 Persistence and Serialisation


What does persistent object mean and where should such objects be stored?

Persistent object is an object that has the capability to exist longer as opposed to most objects
in JVM that have a very short life span. When there are no references to the objects, the memory
space will be collected by the automatic garbage collector.
If the object is being used and there is reference to that object, it will still be removed at one
point. Therefore, the solution is to keep objects at JVM host. The class that allows this to
happen is java.util.Vector which contains data state and java.util.Properties that has system
persistence.
Serialised object controls the data that distribute information about the object behaviour to a
few specific parts such as variable classification, method; public, private and protected when

30
persistent objects have been identified. Serialised objects allow object to move from one JVM
another JVM whether on the same device or a remote machine.

Activity 3.2
To test your understanding, answer the questions below:

1. Explain in your own words, your understanding of persistent objects and serialised
objects.
2. Why is stream concept essential for network programming?
3. What do you understand about byte streams and character streams?

3.5 Summary
The java.io package provides the programmer various choices to read and write data bytes and
characters. Upon mastering the concept of streaming, you can use it easily in many important
parts in developing software and network applications.

Programmers can read numbers, sequences, arrays, strings and other data types using filter
streams, filter readers and writers as well as low level streams. Hence, communication of data
can be done when using streams in application.

References
Hughes. M, Shoffner. M and Hamner. D (1999), Java Network Programming- A Complete
Guide to Networking, Streams and Distributed Computing,Second Edition, Manning

31
Niemeyer. P and Leuck. D (2013), Learning Java, 4th edition, O’reilly

Reilly. D and Reilly. M (2002), Java Network Programming and Distributed Computing,
Addison-Wesley

Stevens .W.R, Fenner. B and Rudoff. A.M (2004)Unix Network Programming, The Sockets
Networking API, Volume 1,Third edition, Addison-welsley professional computing series

32
BLANK PAGE
Unit 4 Threaded Application

4.0 Introduction
Nowadays application systems are user friendly. One of the reasons is because many
applications can be generated at a time and it fulfils user requirements.
These applications can be done by Java using multithreading application. Multithreading is
used in Java network programming and web application. It is very important since there are
frequent interactions like listens to request, reply the request, data processing and updating data
between client and server.

You will learn multithreading concept, develop multithreading applications, multithreading


communication, multithreading synchronisation and lastly threading assembly of particular
groups. Good understanding of this unit can help you in learning the subsequent units.

4.1 Objectives
At end of this unit, you should be able to:
• explain the concept of threading and multithreading
• develop threading application by using java.Lang.Thread class and implement
java.lang.Runnable
• explain when java.lang.Runnable can be used
• describe five methods provided by Java to control threads
• write application related to synchronisation
• write application related to threading communication
• write application to implement thread grouping

33
4.2 Thread Overview
Unique features of Java include providing threading application which enables implementation
of multiple processes at a time. There are differences between single threading, multi-process
and multithreading as shown in Table 4.1.

Table 4.1: Differences between Single Thread, Multi-Process and Multithreads

For more information on threading, please browse through


http://www.cmi.ac.in/~madhavan/courses/pl2006/lecturenotes/lecture-notes/node65.html
www.cs.usfca.edu/~parrt/course/601/lectures/threads.html
goose.ycp.edu/~dhovemey/spring2011/cs365/lecture/lecture17.htm
xml.cs.nccu.edu.tw/courses/java/java2010/slides/Lec7!JavaThreads.ppt

Activity 4.1
Answer questions below to test your understanding.

1. What do you understand with the concept of threading? Explain.


2. Why threads are important in network programming?

34
4.3 Multithreading

Why are most web servers developed based on multithreading application?

Java and other programming languages support multithreading applications.


Java provides the java.lang.Thread class to execute threading. However, separate threading
programs are represented by java.lang.Runnable class. Figure 4.1 shows the application process
that manages more than one subprocess.

Figure 4.1: Application process that manages more than one subprocess

4.3.1 Develop multithreading application using thread class


The java.lang.Thread class provides methods like start, suspend, resume and stop. This class
also controls a few aspects such as threading priority or names associated with it. The easiest
way to use a Thread class is through extends and ignoring the run( ) method. By ignoring run(
) method, threads are able to work well.

Example 4.1: Create Threading by Using Extends Thread

// Extends Thread Class


class BasicThread1 extends Thread {
int nobebenang;
//This method is called when thread is being executed
public void run( ) {
System.out.println ("I am Threads" + nobebenang);
}
public BasicThread1(int nom) {
nobebenang=nom;
}
public static void main (String args[ ]) {
// Create and start threads
Thread thread1 = new BasicThread1(1);
Thread thread2 = new BasicThread1(2);

35
thread1.start( );
thread2.start( );
}
}

4.3.2 Create multithreading application using runnable interface

Java differs from C++. Java only supports one inheritance. Therefore, class that extends
java.lang.thread could not be inherited by any other classes. As an alternative,
java.lang.Runnable interface can be implemented. Runnable interface differs from extends
Thread by defining single run( ) method that needs to be implemented. run( ) method to be
implemented is as below:

public void run ( )

The steps to create thread using Runnable interface are as below:


(a) Executing Runnable Interface

public class RunnableThread implements Runnable {


//program block
}
(b) Define run( ) method

public void run( ) {


//program block
}

(c) Create Temporary Variable from the Generated Class so that it is Easier to Manipulate

RunnableThread rt = new RunnnableThread( );

(d) Create Temporary Variable from Thread Class and Send Temporary Variable to Thread
Class Constructor

Thread t = new Thread (rt);

(e) Call Start( ) Method

t.start ( );

Example 4.2: Threading Program Implementing Runnable Interface


public class RunnableThread implements Runnable {
public void run( ) {
System.out.println ("Executing runnable interface thread");
}
public static void main ( String args[]) {
RunnableThread rt = new RunnableThread( );
//Creates first thread
Thread t1 = new Thread (rt);
//Create second thread

36
Thread t2 = new Thread (rt);
t1.start ( );
t2.start ( );
}}

Activity 4.2
Answer questions below to test your understanding.
1. List down the advantages of using Runnable interface.
2. Is it true that program which extends thread can be implemented in Runnable interface?
State your reason.
3. Build a SimpleThread class which extends java.lang.Thread. This class should have
constructor that accepts String as an argument. Create three objects from this class. For
each created object, start the thread and display strings that represent each object.
4. Build a SimpleRunnableThread class which implements java.lang.Runnable. Create
SimpleRunnableThread object then three objects from java.lang.Thread class which
accept object SimpleRunnableThread as an argument. Start the thread for each created
object.

4.4 Controlling Thread


Creating threads is not the only specification in Java. There are other control specifications like
sleep, suspend, stop, interrupt, resume, yielding CPU time and wait until the thread ends.

4.4.1 Sleep( ) Method


Sleep( ) method stops the thread that is being executed for a certain period of time. As an
example, sleep(10000) means that the thread sleeps or stops for 10000 millisecond. Sleep( )
method throws InterruptedException and usually this method is called in try block.

Example 4.3: Sleep Thread with InterruptedException

class BasicThread1 extends Thread {


// this method is called when thread being executed
int nobebenang;
public void run( ) {
System.out.println ("I am thread" +nobebenang);
int count;
for( count=0; count < 10; count++) {
System.out.print(count +” ”);
}
try{
//Sleeps for 1000 millisecond
Thread.sleep(1000);
System.out.println(“Thread being stopped for
1000 millisecond”);
}
catch (InterruptedException ie) {
System.err.println(“Just for a short while…”)
}
}
public BasicThread1(int nom) {

37
nobebenang=nom;
}
public static void main ( String args[]) {
// Creates and starts thread
Thread thread1 = new BasicThread1(1);
thread1.start( );
System.out.println(“Press any keys to stops thread”);
System.in.read( );
thread1.stop( );
}
}

4.4.2 Stopping thread


Thread can be stopped even when the process is not completed. This can be implemented by
sending Thread.stop( ) method to stop the particular thread.

Example 4.4: Program to Stop Thread


class BasicThread1 extends Thread {
// this method is called when thread being executed
int nobebenang;
public void run( ) {
System.out.println ("I am thread" +nobebenang);
int count;
for( count=0; count < 10; count++) {
System.out.print(count +” ”);
}
try{
//Sleeps for 100 millisecond
Thread.sleep(100);
System.out.println(“Thread being stopped for
100 millisecond”);
}
catch (InterruptedException ie) {
System.err.println(“Just for a short while…”)
}
}
public BasicThread1(int nom) {
nobebenang=nom;
}
public static void main ( String args[ ]) {
// Creates and starts thread
Thread thread1 = new BasicThread1(1);
thread1.start( );
System.out.println(“Press any keys to stops thread”);
System.in.read( );
thread1.stop( );
}
}

38
4.4.3 Suspend and resume threads
Thread can be stopped without ending the thread by suspending its operation. Suspension of
thread operation can be resumed again. Suspension of thread operation can be implemented by
using Thread.suspend( ) method. Thread.resume( ) method is used to resume the pending
thread. Program block below shows the steps of how to suspend and resume thread.

.
.
.
thread1.suspend( );
try { Thread.sleep(2000); }catch(InterruptedException e)
{
System.out.println(“Suspend thread operation”); }

thread1.resume( );
try { Thread.join( ); } catch (InterruptedException e) {
System.out.println(“Resume operation “); }
.
.
.

4.4.4 CPU yield time using the Yield( ) Method


There are a few situations where threads need to wait for a special event before they can be
implemented. System performance and user experience can be upgraded by entering code areas
that release CPU time to other threads. As an example, it is better for the system to release time
from CPU rather than let the threads to sleep for long time interval. Please check out the
program below:

public void run( ) {


// Provide CPU yield time
System.out.println ("BEGIN!" + thread1.getName( ));
for (int i = 1; i <= maxcount; i++){
System.out.println (i + ". " + thread1.getName( ));
Thread.yield( );
}
System.out.println ("DONE!" + thread1.getName( ));
}

4.4.5 Wait until thread end


There are situations where it is better to wait until thread ends its operations before the
following operation is started. As an example, when attempt to achieve result by calling a
method, or reading another variable, the operation has to wait till the variable is updated. The
best way to wait for threads to end is by using Thread.join( ) method.

39
Example 4.5: Program Waits Until Threads Ends
class BasicThread1 extends Thread {
int nobebenang;
// This method called when thread being executed
public void run( ) {
System.out.println (" I am thread" +nobebenang);
try {
// Sleeps for 10000 millisecond
Thread.sleep(10000);
System.out.println(“ Thread being stopped for 100 millisecond ”);
}
catch (InterruptedException ie) {
System.err.println(“ Just for a short while…”)
}
}
public BasicThread1(int nom) {
nobebenang=nom;
}
public static void main (String args[]) throws Exception {
// Creates and starts thread
Thread thread1 = new BasicThread1(1);
thread1.start( );
//Wait until thread end.
System.out.println(“ Wait until thread end”);
thread1.join( );
System.out.println(“Threads have end”);
}
}

Activity 4.3
Answer questions below to test your understanding.

1. List down thread control methods. State the function and implementation of each
method.
2. Build a SimpleSleepThread class by implementing Runnable. Create an object Thread
and start the thread. In run method, let the thread sleep for 10000ms. Display strings
before and after the thread sleep. Is there any noticeable time difference between the
two strings displayed? Why or why not?

4.5 Synchronisation
Synchronisation can prevent concurrent data access from two or more threads and therefore
ensures the security of data integrity. However, there are disadvantages if synchronisation is
not applied appropriately.
Provide a consequence where synchronisation is used wrongly.

Consideration that needs to be taken when designing multithreads is data access conflict.
Application integrity is in stake when there are two or more threads attempting to access the

40
same source and there is no mechanism to overcome this situation. In Java, there are two
mechanisms to avoid simultaneous access to source as shown in Figure 4.2.

Figure 4.2: Synchronisation mechanisms

4.5.1 Method level synchronisation


When handling multithreads, a programmer need to consider situation whereby two or more
threads tried to access the same variable. There will be unstable situation, if there are threads
that want to modify the state of the variable.

Figure 4.3 shows how three threads try to access Counter class at the same time.
Therefore, synchronise method prevents two threads implementing methods on the same object
at a time. When synchronised method is called, threads will lock the object so that when other
threads try to execute synchronised method, it will find that the particular object is locked.
The thread will be in suspended mode until the method is released. In Figure 4.4, when
synchronised class Counter is locked, second and third threads will wait.
This will prevent occurrence of simultaneous access. Objective of synchronisation is to avoid
damages to data or missing data.

Figure 4.3: Simultaneous access to counter class

41
Figure 4.4: Safe threads being accessed from threads class method

Program 4.6(a) show steps to increase counter using Counter class which implements
synchronised method. There are two types of synchronised methods, such as:

public synchronised void increaseCount( ) {


int count=countValue;
count+=1;
countValue=count;
}

And

public synchronised int getCount( ) {


return countValue;
}

Example 4.6: Programme for Method Level Synchronisation


(a) Counter Class and Synchronised Method

public class Counter{


private int countValue;
public Counter( ) {
countValue=0;
}
public Counter(int start) {
countValue=start;
}
//synchronized method to increase counter
public synchronised void increaseCount( ) {
int count=countValue;
try {
Thread.sleep(5);
}
catch(InterruptedException ie){}
count+=1;

42
countValue=count;
}
public synchronised int getCount( ) {
return countValue;
}
}

(b) CountingThread Class


public class CountingThread implements Runnable {
Counter myCounter;
int countAmount;
public CountingThread(Counter counter, int amount)
{
myCounter=counter;
countAmount=amount;
}
public void run( ) {
for(int i=0; i<countAmount; i++) {
mycounter.increaseCount( );
}
}
public static void main(String args[])throws Exception {
Counter c= newCounter( );
Runnable runner = newCountingThread(c,10);
System.out.println("Start Counting Threads");
Thread t1 = new Thread(runner);
Thread t2 = new Thread(runner);
Thread t3 = new Thread(runner);
t1.start( );
t2.start( );
t3.start( );
//Wait until all three threads end
t1.join( );
t2.join( );
t3.join( );
System.out.println("Counter Value is"+c.getCount( ));
}
}

4.5.2 Preventive level synchronisation


Method level synchronisation is an effective technique to handle problems with simultaneous
access. However, if threads are not designed as secure threads and there exist classes that
cannot be changed by the programmer, preventive level synchronisation would be the best
choice. Preventive level synchronisation still uses synchronised as the keyword. The following
code shows syntaxes for synchronised block.

Synchronised (Object obj)


{
...
}

43
Example 4.7 is a program using preventive level synchronisation approach. Access and
changes are done in the run( ) method.

Activity 4.4
Answer questions below to test your understanding.
1. What do you understand about method level synchronisation? Explain the function.
2. Why Java creates preventive level synchronisation? Explain your answer.
3. Build a SimpleSynchronised class by implementing Runnable. Create a count( ) method
which is synchronised and variable count in SimpleSynchronised class. In the count( )
method, increase count value to one each time the method is called and let thread sleep
for 1000ms. In the run( ) method, call for run method. Display count value after count(
) method is called. After the completion of running this class, modify count( ) method
by removing synchronised word. Run this class again. What is the difference in display
that you notice this time?

Example 4.7: Source Program for Preventive Level Synchronisation


public class SyncBlock implements Runnable {
StringBuffer buffer;
int counter;
public SyncBlock( ) {
buffer = new StringBuffer( );
counter=1;
}
public void run( ) {
synchronized(buffer);
{
System.out.print("Starts Preventive Synchronisation");
int tempVariable =counter++;
String message ="Count value is:"+tempVariable
+System.getProperty("line.separator");
try {
Thread.sleep(100);
}
catch(InterruptedException ie){}
buffer.append(message);
System.out.println("Preventive Synchronisation Ends");
}
}
public static void main(String args[])throws Exception {
//Creates variable from SyncBlock class
SyncBlock block = new SyncBlock( );
Thread t1 = new Thread(block);
Thread t2 = new Thread(block);
Thread t3 = new Thread(block);
Thread t4 = new Thread(block);
t1.start( );t2.start( );
t3.start( );t4.start( );
t1.join( );t2.join( );t3.join( );t4.join( ); //Waits until all threads ends
}
}

44
4.6 Communication between Threads
Threads interact with themselves and communicate with other threads to execute a certain
operation. There are two choices in interaction between threads; by using pipe communication,
the notify( ) method and the wait( ) method.

4.6.1 Pipe communication


This communication uses pipe to send data from one process to another process.
Threads are sent directly using input and output streams which are linked together.

Two ways communication happens when either one end of the pipe sends to another thread.
Threads listen or communicate with other threads. Two pipes can be used. A thread can have
two way communications with other threads.

Steps to create thread interaction are as shown below:


(a) Build pipe to write.
(b) Build pipe to read, and connects to output pipe.
(c) Build thread pipe from class that has been created to write into it.
(d) Starts thread.
(e) Reads thread data.

4.6.2 Notify thread to wait for a particular event


Most events are in series that waits for one event to complete before another event can take
over. This situation also happens to threads interacting with each other by informing other
threads about the thread’s status.

The method of thread waiting for completion of event execution is one of synchronisation
methods. The involved class comes from java.lang.Object which supports maintenance of
thread in waiting during implementation of wait( ) method. There will be monitoring and the
waiting thread will be suspended until a call from notify( ) or notifyAll( ) method.

Steps to implement synchronisation which notify waiting threads are as shown below:
(a) Build thread from class that has been created.
(b) Start thread.
(c) Wait for thread notification which traces the event.
(d) Inform user the return of wait( ) method.

Activity 4.5
Answer questions below to test your understanding.

(a) What do you understand about communication between threads?


Explain how pipe communication and waiting thread notification can be implemented.
(b) Build class SimpleNotifyWaitThread by implementing Runnable.
Create waitHere( ) and notifyHere( ). Inside waitHere method call the wait( ) method.
Inside the notifyHere( ) method call notify( ) method.
Create two thread objects. The first thread will be calling waitHere( ) method, and the
second thread will be calling notifyHere( ) method. Display related strings inside each
called method. What can you conclude from the displayed strings?

45
4.7 Thread Grouping
Apart from creating and executing individual thread, they also can be assembled into certain
groups as shown in Figure 4.5.

Figure 4.5: Thread grouping

Thread operation, such as:


• suspend,
• resume,
• stop, and
• interrupt

can be executed individually. API Java provides support to thread group in ThreadGroup class.
This class represent collection of threads and provide method which acts as the method to
individual thread in thread collection.
It also provides a way to collect information about related threads with number of threads and
the address of thread location in the group.

Thread group can be created by using two constructors which are available in ThreadGroup
class, namely public ThreadGroup(String) and public ThreadGroup(ThreadGroup
parentGroup, String name). Apart from this, thread group can also be created using three
constructors which are available in java.lang.Thread class, Thread(ThreadGroup group,
Runnable runnable), Thread(ThreadGroup group, String name) and Thread (ThreadGroup
group, Runnable runnable, String name).

Group operation can be implemented when threads are assembled into group.
Number of active threads from the list of threads can be accessed by calling ThreadGroup
method.

Steps to create thread group, thread and execute list( ) method are as below:
(a) Create thread group.
(b) Create child group to thread group.
(c) Build a few threads to parent and child thread to a particular group of thread.
(d) Execute related method like list( ) method.

46
4.8 Summary

In this unit you have learnt about threading using the java language. It is hoped that you now
know the different types of threads, how to develop multithreading applications using the
thread class and runnable interface. You have also learnt how to control threads,
synchronisation and communication between threads and thread groupings.

47
References
Apple (2014), Threading Programming Guide, Available from:
http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Multithreadi
ng/Multithreading.pdf, [18 December 2014]

Calvert. K. L and Danahoo. M.J (2011), TCP/IP Sockets in Java Practical Guide for
Programmers, Second Edition, Elsevier

Doug. L (1999), Concurrent Programming in Java, Second Edition, Design Principles and
Patterns, Addison Wesley,

Graba. J (2013), An Introduction to Network Programming with Java-Java 7 Compatible,


Third Edition, Springer

Holub. A (2000), Taming Java Threads

Hyde. P (1999), Java Thread programming

Ibm developmentWorks, Introduction to Java threads

Tutorialspoint (2014), Available from:


http://www.tutorialspoint.com/java/java_multithreading.htm, [8 January 2015]

48
Unit 5 URL

5.0 Introduction
This unit we discuss the basic concept of URL and its application in Java programming. When
applying the usage of URL class, you should not worry about protocols, data format and the
communication between the computers on the network. In this unit we focus on how the URL
is communicated to the Java programme. Once the Java programme has received the URL, the
programme will automatically ensure that the end user will receive the data.

5.1 Objectives
At the end of this unit, you should be:
• explain the concept of URL and its formats
• differentiate the three URL classes in Java
• describe a programme that uses the URL class to create and read information from the
server

5.2 URL Overview

When surfing the Internet, do you ever wonder about the address format of the websites that is
typed in? What does the address actually represent?

URL (Uniform Resource Locator) is a reference (address) to a resource on the Internet. If we


are surfing the Internet, the term URL is not a strange term. URL refers to the fastest way to
retrieve the information from the World Wide Web (WWW). Most URLs refer to a specific
file in a network. Apart from that, the URL also links us to other sources to retrieve data that
is databases and output instructions.

The following is the URL addressing format used by Sun Microsystems

Figure 5.1: URL used by Sun Microsystems

In Figure 5.1, we can notice that the URL consists of 2 main components which are:
• the protocol identifier
• the resource name
The Protocol Identifier and the Resource Name are separated by a colon (:) and two forward
slashes (//). The Protocol Identifier defines the name of the protocol used to access the host’s
source. The Hypertext Transfer Protocol (HTTP) is a widely used Protocol Identifier to access
hypertext documents on the WWW.

49
HTTP is one of many protocols used to gain access to all sorts of data source on the network.
Other protocols are File Transfer Protocol (FTP), Gopher, File and News Resource Name is
the complete address to the information source. The format of the Resource Name depends
completely on the protocol that is being used. For HTTP protocol, Resource Name will consist
of one or more of the following components:

• Host Name - Name of the machines where the source is located


• File Name - Pathname of the file in a machine.
• Port Number - The port number that needs to be connected
• Reference - Reference to a specific location(anchor) in the source

The host and file names are required whilst the port number and the location reference are
optional when surfing a web address. For example, the URL resource for HTTP needs to be
specified with the server (host name) in the network as well as the path to document on that
machine. We may specify the port number and reference file in the URL Figure 5.1 if we like.
The URL for the Java website is http://java.sun.com:80/index.html.

Therefore, a complete schematic overview of the URL is as in Figure 5.2:

Figure 5.2: The URL schematics

Website
For more information you may refer to the RFC 2396: Uniform Resource Identifier (URI):
Generic Syntax revised by RFC 2732: Format for Literal Ipv6 Address in URLs.
We encourage you to visit the following website:
http://www.faqs.org/rfcs/rfc2732.html

5.3 URL and Java


Java has made some specific packages to interact with URLs. Apart from re-using the URL in
the packages, the software developer can freely extend and add-on the needed protocols into
the URL class. Amongst the classes developed to interact with the URL are:

• java.net.URL
• java.net.URLConnection
• java.net.HTTPURLConnection

All these three classes are different and consist of various functions. Comparison can be done
by its performance when reading/writing to/from the network.

Website
URL classes in Java are explained comprehensively in the API documentation. You can surf:
http://java.sun.com/j2se/1.4.2/docs/api/java/net/URL.html for a more detailed explanation.

50
5.4 URL classes
URL (Uniform Resource Locator) classes are references to the resources in the World Wide
Web (WWW). URL may be a reference to a file, a web site, an FTP site, a newsgroup, an e-
mail and anything of that such. The most frequently used URL schematics are:

• http://www.hotmail.com
• ftp://www. myvista.zou.ac.zw
• telnet://pkrisc.cc.ukm.my
• https://www. myvista.zou.ac.zw:8133

URL schematics above still follow the format as in Figure 5.2. Each field in the URL can be
parsed into separate URL classes.

Website
What is the name of the Java package to define URL classes?
The answer can be found at:
docs.oracle.com/javase/7/docs/api/java/net/URL.html

5.4.1 Creating a URL


The easiest way to create an URL object is in the form of a string. This is the simplest form to
be read.
An example of URL for learning management system at Zimbabwe Open University, ZOU is:
http://www.myvista.zou.ac.zw/
In Java programming, we can represent the URL as a string to creating the URL object, as seen
below:
URL myvista = new URL (“http://www.myvista.zou.ac.zw /”)

The URL object created represents the absolute URL. The Absolute URL contains all the
information required to access the resources. The constructor used to create the URL object is
based on the following command:

URL ( String stringURL)

Apart from that, we can also create the URL object from a relative URL address.

5.4.2 Creating relative URL


The relative URL contains enough information for the current URL to access relative resources.
The relative URL is mainly used in hypertext documents such as the HTML file. For example,
if we have a HTML file, courses.html which contains a link to another HTML file, results.html.
Both of these files will be located in the same directory and in the same machine. The link from
courses.html to results.html is:

<a href = “results.html” > Results </a>

URL address like this is referred as Relative URL. The specified URL is relative to the
courses.html file. In this case, the locations of both files are identical.
Java programming allows us to create URL objects that are relative to a base URL
http://www.myvista.zou.ac.zw /courses/ seen below:

URL myvista = new URL (“http://www.myvista.zou.ac.zw/nyandoro/nk/steve”);


51
URL nk3223 = new URL (myvista, “nk3223.html”);
URL nk2933 = new URL (myvista, “nk2933.html”);

Excerpts of the above code use URL constructor to create a URL object from the base and
relative URL. The general form of the URL constructor discussed above is as shown below:

URL (URL baseURL, String URLrelative)

This constructor can also be used to create URL objects as reference in hypertext documents.
For an example, the document nk3223.html contains an anchor named NEWS.
We can use the relative URL constructor to create a URL object like the following:

URL nk3223News = new URL(myvista, “#NEWS”);

5.4.3 Other URL builders


Other than the two constructors mentioned above, Java also provides programmers other
facilities to create URL objects. For example, we can develop a program that allows users to
choose the protocol, host name, port number and file name.

Although, we can use both techniques above, it is still difficult since we would need to create
a string for a complete URL address that contains several URL field. To solve this problem,
Java also provides few URL constructor methods to overcome this problem.

The mentioned constructor is by creating URL objects from the protocol, host names and file
names. The following excerpt creates a URL to the file nk3223.html at the
www.myvista.zou.ac.zw website:
URL nk3223 = new URL (“http”, “www.myvista.zou.ac.zw”,“/nyandoro/nk/steve
/nk3223.html”);

The command above is similar to the command to create a URL object with complete URL
address:
URL nk3223 = new URL
(“http://www. myvista.zou.ac.zw/nyandoro/nk/steve/nk3223.html”);

In the above case, parameter value that needs to be stack into URL class is the protocol, host
name and link name to the file name.

Note
If a file name consists of forward slash at the beginning, this means the file is located at the
root directory of the host
We may also consolidate the port number if the file is located at a specific port, for example if
the port number is 80:
URL tk3223 = new URL (“http”, “www. myvista.zou.ac.zw”, 80,
“/nyandoro/nk/steve/nk3223.html”);
The above excerpt is exactly the same as the URL object created below:
URL nk3223 = new URL (“http://www. myvista.zou.ac.zw: 80/nyandoro/nk/steve/
nk3223.html”);
The URL object explained above is a once-off activity, meaning once the object has been
created, we cannot re-specify any of the attributes that is the protocol, the host name or file
name or the port number.

52
5.4.4 MalformedURLException exception
For every URL constructor discussed above, there may be MalformedURLException
exception. This exception happens when the constructor does not receive parameters or refers
to an unknown protocol.
Normally, we handle and tackle each exception in URL builder by using the try/catch handlers
as below:
try {
URL myURL = new URL(…);
}catch ( MalformedURLException e) {

//catch exception here

}
For further information on ways of handling exceptional errors, please refer to Unit 1.

5.3.5 URL parser


The URL class has a variety of facilities that allows us to query URL objects.
Information retrieved will inform us of the protocol used, the host name, the port number and
the file name. The methods used to access the URL class information are:
• getProtocol
 Returns the component identity protocol for URL.
• getHost
 Returns the URL’s component host name.
• getPort
 Returns the URL’s port number. The getPort method returning integer
 type port number. If a port number is not set, the returned value is -1.
• getFile
 Returns the URL’s file name component.
• getRef
 Returns the URL’s anchor component.
We can use the getXXX methods to retrieve information about a URL to create URL objects

By using methods as discussed, users do not need to use parsers URL anymore.
By creating the URL object and using the appropriate methods, we can retrieve all the
information we need as in the program below:
protocol = http
host = java.sun.com
file = /docs/books/tutorial/index.html
port = 80
ref = DOWNLOADING

import java.net.*;
import java.io.*;
public class ParseURL {
public static void main(String[] args) throws Exception {
URL aURL = new
URL("http://java.sun.com:80/docs/books/"
+ "tutorial/index.html#DOWNLOADING");

53
System.out.println("protocol = " + aURL.getProtocol( ));
System.out.println("host = " + aURL.getHost( ));
System.out.println("filename = " + aURL.getFile( ));
System.out.println("port = " + aURL.getPort( ));
System.out.println("ref = " + aURL.getRef( ));
}
}

The program above will display the following output:

Your Idea
Can a client connect to an http server on another port beside port 80?
If no, please give the reasons and if yes what needs to be done by the client and the server?

5.5 Reading Directly From the URL


Upon successfully created and invoked URL class, we now can use the openStream( ) method
to read an incoming stream from the URL. The openStream( ) method returns the
java.io.InputStream object if the read is successful. Therefore, any stream from URL can be
read using the InputStream class.

The program in Example 5.1 uses openStream( ) method to retrieve the InputStream from the
URL http://www. myvista.zou.ac.zw. The input stream from the URL is buffered using the
BufferedReader and then it is displayed unto the user’s screen.

Example 5.1: Using openStream( )


import java.net.*;
import java.io.*;
public class URLReader {
public static void main(String[] args) throws
Exception {
URL yahoo = new URL("http://www. myvista.zou.ac.zw/");
BufferedReader in = new BufferedReader(
new InputStreamReader(
yahoo.openStream( )));
String inputLine;
while ((inputLine = in.readLine( )) != null)
System.out.println(inputLine);
in.close( );
}
}

When the above program is executed, we can read the HTML tags (instructions) as well as the
contents of the HTML files located at http://www. myvista.zou.ac.zw. The file contents will be
displayed unto the command window. If there is no output displayed or if an exception is

54
returned, it would mean that the program does not recognise the www.myvista.zou.ac.zw
address.
To solve that error, make sure that the computer is connected to the Internet. If the machine
you are using is connected to the internet through the proxy host, you will need to set the proxy
host so the programme can find the server www. myvista.zou.ac.zw.

We can set the proxy host using the command line. The command line depends on the proxy
network configuration. Normally, the proxy host is located at a specific port. You may need to
request for assistance from your network administrator. Use the following command based on
the operating system on your machine:

UNIX
Java -Dhttp.proxyHost=proxyhost[-Dhttp.proxyPort=portNumber]URLReader

DOS shell (Windows 95/NT/Win2K)


Java -Dhttp.proxyHost=proxyhost[-Dhttp.proxyPort=portNumber]

5.6 Connecting the URL


The function of the URL class is to control the connection between the Java program and URL
on the network. Upon successful creation of the URL object, we can use the openConnection
method to connect to URL server. As an example, we can make a connection to the FTSM
website using the programme excerpts below:

try {
URL ftsm = new URL("http://www. myvista.zou.ac.zw/");
URLConnection ftsmConnection = ftsm.openConnection( );
} catch (MalformedURLException e){// new URL( ) failed
...
} catch (IOException e) { // openConnection( ) failed
...}

The openConnection method actually does the following:


• Create a new URLConnnection class (if it does not yet exist)
• Initialisation
• Connect to the URL; and
• Returns the URLConnection object

If any problem should arise for example the FTSM server cannot be accessed, the method
openConnection will return an IOException. If no problems arise, we will be connected to the
URL as inserted into the URL class. The URLConnection object that is returned by the
openConnection method can now do read and write operation unto the connection. The
URLConnection class will be discussed in the next unit.

Activity 5.1
Answer the question to test your understanding:
Write a programme that uses the URL class and the openStream( ) method to read and
write interactively the contents of a website.

55
5.7 Summary

URL (Uniform Resource Locator) is a reference (address) to the resources on the Internet. You
need the URL of your favourite website so you can locate files on the Internet.
URL is the most important element in making the HTML capable of being a networked
hypertext language. URLs can be references to files, websites, ftp sites, email addresses and
other resources. Comprehension of URLs is essential in Internet communication.
At the end of this unit, you have been exposed to writing of Java programming involving
application of URL classes in network programming. You need to familiarise to elements like
creating URL, relative URL, URL parser and so on which will be used to improve your network
programming skills.

References
Hughes. M, Shoffner. M and Hamner. D (1999), Java Network Programming- A Complete
Guide to Networking, Streams and Distributed Computing,Second Edition, Manning

56
Oracle (2014), Class URL, Available from:
http://docs.oracle.com/javase/7/docs/api/java/net/URL.html [ 18 December 2014]

Pitt. E (2006), Fundamental Networking in Java, Springer

57
BLANK PAGE
Unit 6 URL Connection

6.0 Introduction
In this unit we discuss the basic concept of URLConnection class and its usage in Java
programming. The URLConnection class is an extension of the URL class and has different
and specific functions compared to the URL class.

6.1 Objectives
At the end of this unit, you should be able to:
• explain the usage of URLConnection class in Java
• write a program to create, read and write information from client to server using
URLConnection class

6.2 Overview of URLConnection


The URLConnection class consists of many methods that enable communication with URL in
a network. The main function of the URLConnection class is to read and write to network. Like
URL class, the URLConnection class is not limited to any particular protocol.

Protocols that are supported by the URL and URLConnection class depend on the version of
Java used or in specific Virtual Machine (VM). Protocol supported by JDK from Sun may be
different from protocol supported by VM for Internet server.

Table 6.1 shows the main protocol supported by some VM. There are other protocols supported
by VM but not shown in the table.
For protocols not supported by VM, we can extend the function of URL class by writing and
setting the protocol defined by users.

Table 6.1:Protocols Supported by URL and URLConnection Classes

Your Idea
What is the difference between java.net.URL and java.net.URLConnection?

58
6.3 Reading and Writing Using URLConnection

The program in Example 6.1 executes the functions similar to URLReader program in Unit 5.
Nevertheless, there are some obvious differences between the two programs. Unlike the
previous program, this program gains InputStream by using the openConnection method. Next,
it creates BufferedReader on input stream and reads it. The bolded words at the bottom show
the differences from the previous URLReader program.

The output of Example 6.1 is exactly the same as the URLReader program. The difference is
that URLReader reads the information directly from the URL connection using openStream( )
method. In this program, data is read using URLConnection object. We use URLConnection
to not only read but to execute other function like writing.

Example 6.1: The Use of URLConnection

import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL ftsm = new URL("http://www. myvista.zou.ac.zw/");
URLConnection ftsmconn = ftsm.openConnection( );
BufferedReader in = new BufferedReader(
new InputStreamReader(
ftsmconn.getInputStream( )));
String inputLine;
while ((inputLine = in.readLine( )) != null)
System.out.println(inputLine);
in.close( );
}
}

6.4 Writing Using URLConnection


Many websites allow users to input information for processing and analysis at the server. Data
processing by server is usually done using scripts and certain delivery methods. Any website
that allows user input has FORM tags. In brief, FORM tag is:

<FORM METHOD=”POST” ACTION=”CGI-BIN/Process” >


<…>
</FORM>

What FORM tag does is that once certain data is typed and the Submit button is clicked, the
Web server will write the data to the URL network. At the server, that data will be processed
using the application ACTION tag.

Server script like Perl is usually located in the „/cgi-bin‰ directory (depending on the script
type used by the server). When CGI script receives data, it will process that data and send
information in HTML format.

59
CGI script uses either GET or POST method to read data from client. The POST method is
used for reading input using standard input. Standard input allows data to be sent in streams
and in unlimited size. This is because data is sent in string. The POST method is safe since
string query at URL is not revealed to the user. Unlike the GET method, the string query will
be revealed to the web browser users. By using the GET method, the size of the data is limited.

Java programs can also interact with CGI script or any server script. This is done by allowing
data writing to URL and directly making prepared the data to server. Below are the steps to
achieve the above objective:

(a) Create URL.


(b) Open connection to the URL.
(c) Set output capability to URLConnection.
(d) Get the output stream from the connection. The output stream is taken from standard
input for cgi-bin script at the server.
(e) Write to output stream.
(f) Close output stream.

Example 6.2 shows the program for writing data to cgi-bin script or server using
URLConnection class.

The CGI script named processes has been placed in the OUM server at the address,
http://opt.oum.edu.my/cgi-bin to be used by the program in example 6.2.

Below is the CGI script written in Perl language, this script will accept character string from
the client and send the same string in reverse order back to the client.
Do not worry if you do not understand the script content as it is not included in the scope of
this course. If you are interested in learning how to write server script and further information
on GET and POST methods; we encourage you to take the elective course CBWP2203 - Web
Programming.

#!/usr/bin/perl -wT
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
@pairs = split(/&/, $buffer);
foreach $pair (@pairs)
{
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
# Stop people from using subshells to execute commands
$value =~ s/~!/ ~!/g;
$FORM{$name} = $value;
}
print "Content-type: text/plain\n\n";
print "$FORM{'string'} reversed is: ";
$foo=reverse($FORM{'string'});
print "$foo\n";
exit 0;

60
Does CGI script need to be placed in “cgi-bin” directory? Is it the server or the client that
dictates where CGI scripts are to be placed?
Example 6.2: Sample Usage of the URLConnection
import java.io.*;
import java.net.*;
public class URLReverse {
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("Usage: java URLReverse "
+ "string_to_reverse");
System.exit(1);
}
String stringToReverse = URLEncoder.encode(args[0]);
String stringToReverse = URLEncoder.encode(args[0]);
URL url = new URL("http://opt.oum.edu.my/cgi-bin/proses");
URLConnection connection = url.openConnection( );
connection.setDoOutput(true);
PrintWriter out = new PrintWriter(
connection.getOutputStream( ));
out.println("string=" + stringToReverse);
out.flush( );
out.close( );
BufferedReader in = new BufferedReader(
new InputStreamReader(
connection.getInputStream( )));
String inputLine;
while ((inputLine = in.readLine( )) != null)
System.out.println(inputLine);
in.close( );
}
}

Let us examine the program in example 6.2 and see how it works.

String stringToReverse = URLEncoder.encode(args[0]);

The URLEncoder class is used to encode characters sent to the server. This is to ensure that the
server encodes the characters in the same format.

URL url = new URL("http://opt.oum.edu.my/cgi-bin/proses");


URLConnection connection = url.openConnection( );
connection.setDoOutput(true);

The segment program above creates the URL object and made connection to the local host.
The URLConnection class is used to directly communicate information to the local host server
using the setDoOutput(true) method.

61
Should a connection forbid output, the program will throw an UnknownServiceException. On
the other hand, if the connection allows output, it will return the output stream to the standard
input on the server.

PrintWriter out = new PrintWriter(connection.getOutputStream( ));


out.println("string=" + stringToReverse);
out.flush( );
out.close( );

These instructions send data to the server.

When all output streams are obtained, the program can write data to the output stream and close
it. At the server, the data received from the client will act as the input stream. The process of
output and input stream is as seen in Figure 6.1 below:

Figure 6.1: Output and input stream process

Figure 6.1 shows output stream being used to write data and input stream used to read data
from communication channel. To allow data to be printed, getOutputStream( ) method is called
to return the OutputStream object. To enable reading of data, getInputStream( ) method is
called to return the InputStream object.

Once writing to the communication channel is completed, the flush( ) method will be used to
ensure or force data to be sent to the server if the data is still in the buffer. To write to the
communication channel, the println( ) method is used. The close( ) method is called to close
the communication channel between the client and server.

When process of writing into the URL is completed, the information sent will be processed by
the server and returned to the client through the same URL.
Therefore, to read information from the server, the following code excerpts will be used:

BufferedReader in = new BufferedReader( new InputStreamReader(


connection.getInputStream( )));
String inputLine;
while ((inputLine = in.readLine( ))!= null)
System.out.println(inputLine);
in.close( );

These instructions send information to the client.


Apart from using cgi-bin scripts, servlet, asp and other server scripts may be used.

Try to compile and execute the program in Example 6.2. Use the following instructions to
compile and execute the program. Make sure the Java program is placed in the jdk/bin
directory.

62
Compilation command: javac URLReverse.java
Execution command: java URLReverse hello!
The string of characters URLReverse Hello! will be sent to the Server for processing. You can
also type any other character strings.

Activity 6.1
Test your understanding by answering these questions:
1. Briefly explain the difference between URL and URLConnection.
2. Write a program that uses the URLConnection class and the openConnection method
to read and write information unto an interactive webpage.

6.5 Summary
This unit was a continuation of the previous unit with more detailed explanation by showing
you how to use and apply the URL class. We discussed the function of URLConnection and its
methods for communication with the web server, requesting of header fields, reading feedback
of header field and reading source contents. Finally, by understanding the concept of
URLConnection, you should be able to use methods from URL class and develop Java
programs efficiently.

63
References
Pitt.E, Fundamental Networking in Java, Springer 2006

Oracle corporation (2010), Class URLConnection, available from:


http://download.java.net/jdk7/archive/b123/docs/api/java/net/URLConnection.html, [12
december 2014]

64
BLANK PAGE
Unit 7 HTTPURLConnection

7.0 Introduction
In this unit discuss the basic concept of HttpURLConnection class and its implementation in
Java program. HttpURLConnection class is a subclass of URLConnection class.
HttpURLConnection class is specific to HTTP protocol only.

7.1 Objectives
At the end of this unit, you should be able to:
• explain HttpURLConnection class in Java
• write a program to create, read and write information from and to server using
HttpURLConnection class
• explain GET and POST connection techniques

7.2 Overview of HttpURLConnection


HyperText Transfer Protocol (HTTP) is a popular network application protocol in Internet.
HTTP protocol provides access to documents and files located in the web server. Web server
uses HTTP protocol to request for files or generate CGI script content dynamically, and other
server applications.

Generally, WWW is a collection of hypertext documents which are located in various web
servers and can be accessed by various web browsers or HTTP clients.

7.3 HTTP and Java


Java provides a good support to HTTP protocol. It offers various functions to process HTTP
protocol and resides in java.net package. In the previous unit, you read about URL and
URLConnection classes. Generally, these two classes are not depending on any particular
protocol type. Thus, many protocol types can be applied as long as VM supports those
protocols.

One of the problems of using URL.openStream and URLConnection class is that there is no
suitable method available to get specific information about HTTP protocol that has been sent
by the server. Usually, when we access data using HTTP protocol, the user might want to
observe the access status such as response code status. This specific information cannot be
accessed using URL.openStream or URLConnection.

JDK 1.1 or higher versions, have specific HTTP support functions through the
HttpURLConnection class to overcome this problem. This class is an extension from the
URLConnection class and it provides additional methods and encapsulation field for HTTP
functions.

65
7.4 Create HttpURLConnection Object

Java.net.HttpURLConnection class has a getResponseCode( ) method which returns code


status of http. What are the statuses?

The HttpURLConnection class do not have a general constructor method. We need to call
openConnection( ) method from URLConnection class to use the HttpURLConnection class.
This method will return a URLConnection object.

URLConnection class is the super class for HttpURLConnection class. We have to make sure
that the created object is a member of HttpURLConnection class to access functions in
HttpURLConnection class, as shown below:

URL url = new URL( )


URLConnection conn = url.openConnection( );
if(conn instanceof java.net.HttpURLConnection)
{
HttpURLConnection httpconn = (HttpURLConnection) conn;
// something happens casting
}

Notice that a conn object needs to be caste using the HttpURLConnection class. If an object is
not a member of HttpURLConnection, casting instruction will cause a runtime error.

7.5 Using HttpURLConnection Class


HttpURLConnection class inherits all the functions from its parent class, URLConnection.
URLConnection class inherits the functions and the field from URL class. Generally, functions
and fields inheritted can be automatically accessed by the subclass.

Example 7.1 shows a program to read the status code and feedback message from the web
server. Most URLs will generate normal code “200” and normal entity body for any request
from client. Below are explanations on how HttpURLConnection functions:

(a) Program starts with user entered URL as an argument to the program.
(b) If requested argument is not supplied, the program will be terminated.
(c) If the given URL does not exist, the program will throw exception error and it will
be terminated.
(d) If all the information is correct, then the instruction below will be executed.

Example 7.1: Read Code Status and Feedback Massage

import java.io.*;
import java.net.*;
public class UsingHttpURLConnection {
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("Usage: java UsingHttpURLConnection url");

66
System.exit(1);
}
URL url = new URL( args[0] );
URLConnection connection = url.openConnection( );
if(connection instanceof HttpURLConnection) {
HttpURLConnection httpconn
=(HttpURLConnection)connection;
httpconn.connect( );
int code = httpconn.getResponseCode( );
String msg = httpconn.getResponseMessage( );
if(code == HttpURLConnection.HTTP_OK )
System.out.println(“ Return normal response : “+ msg);
else
System.out.println(“ Return abnormal response : “+msg);
}
}
}

URLConnection connection = url.openConnection( );


The statement above is used to call openConnection method which will be used in
HttpURLConnection class. At the moment, the connection between client and server is not yet
connected. Hereafter, connect( ) command will connect the client to the server.

if(connection instanceof HttpURLConnection) {


HttpURLConnection httpconn = (HttpURLConnection)connection;
httpconn.connect( );
int code = httpconn.getResponseCode( );
String msg = httpconn.getResponseMessage( );
if( code == HttpURLConnection.HTTP_OK )
System.out.println(“Return normal response : “+ msg);
else
System.out.println(“Return abnormal response : “+ msg);
}

The above code will examine whether an object is a member of HttpURLConnection class. If
the tested object is a member to the particular class, the command in the ‘if’ statement will be
executed. Before that, object in the connection needs to be casted to enable access to function
in the HttpURLConnection class.

Hereafter, the status code and the message will be accessed by the program.
Code status 200 shows that the request from the program to the server is successful, or
otherwise it is a failure.

67
7.6 Sending Request Using HttpURLConnection

Observe the URL example below:


http://www.foo.org/cgi-bin/form_submit?name=ahmad. “name” is a parameter which is sent
to the server. Which party determines the parameter name that needs to be sent to the web
server, the client or the server?

HTTP protocol allows the user to send information to the web server for processing. Usually
Common Gateway Interface (CGI) application involves in processing the information in the
web server. There are two methods that can be used in CGI to send data, namely GET and
POST.

In the GET method, data is sent to CGI application using query string. String query is a string
to be connected or located at the end of a URL address to complete the information to be sent
to the web server. An example of string query is:

http://www.foo.org/cgibin/form_submit?name=First%Last&address=

String query is added to the URL after the “?” symbol. Each parameter in the string query will
be separated by the “&” symbol. String query in the above example has two parameters, name
and address. In the GET method, string query will be displayed at the URL web browser
address. String query that is being used in the GET method has limited size.
POST method still uses string query but the size is not limited and the delivery is even more
complex. String query in the POST method is treated as the input output file.

Each URL that is sent to the server needs to be encoded first. This is implemented to assure
that the information sent to the server (of any machine) is able to interpret the same information.
However, there are a few special characters in URL that do not need to be encoded, such as
“:”, “/” and “?”, “&” and “=” symbols.

Your Idea
What is the method suitable to be used, if you would like to send the user’s name and password
to the http server to access a particular website by using tag Form, is it POST or GET? Why?

7.6.1 Sending GET request


Sending a GET request in Java can be done easily. It is as easy as reading the content of a static
resource from the website. The difference is only in URL constructor method whereby all
parameters need to be placed together (string query) and to be encoded before they are sent to
CGI application. The source code below explains how to send a request using the GET method.

try {
//Build url object for URL address and query string
URL url = new URL (URL_address_and_query_string);
//Open connection
InputStream input = url.openStream( );
//Buffer stream for better performance
BufferedInputStream bufIn = new

68
BufferedInputStream(input);
//Repeats until finish reading data
for(;;)
{
int data = bufIn.read( );
//Checks whether finish reading data
if (data = -1)
break;
else
System.out.println((char)data);
}
} catch(MalformedURLException mue){}

7.6.2 Sending POST request


Sending a request using the POST method is slightly complex. The POST method needs a
program to write a parameter to the output stream on the HTTP connection. Therefore, unlike
in the GET method, the openStream( ) method cannot be used in such way. The code below
explains how to send a request using the POST method.

try {
//Build url object for URL address and query string
URL url = new URL(URL_address);
//Get URLConnection object
URLConnection conn = url.openConnection( );
//Specific setting for connection
conn.setDoOutput(true);
conn.setDoInput(true);
//Get output stream for printing
OutputStream output = conn.getOutputStream( );
//Create printing stream to ease writing
PrintStream pout = new PrintStream(output);
pout.println(query_string);
pout.close( );
InputStream input = url.openStream( ); //Open connection
//Buffer stream for better performance
BufferedInputStream bufIn = new
BufferedInputStream(input);
for(;;)// Repeats until finish reading data
{
int data = bufIn.read( );
if (data = -1) // Checks whether finish reading data
break;
else
System.out.println((char)data);
}
}catch(MalformedURLException mue){}

69
Activity 7.1
To test your understanding, answer the questions below:

(a) Write a program which could download a file from a website using
HttpURLConnection interactively.
(b) Empty spaces are reserved characters in URL. It is wrong to use empty spaces in URL.
How can URL be connected by using HttpURLConnection class when there is an empty
space in a particular URL?

7.7 Summary
In this unit we gave you some exposure on the basic concept of the HttpURLConnection class
and its implementation in Java. Although this unit is a continuation of unit 6, it was more
specific into the HttpURLConnection class which is the subclass for the URLConnection class.
We also explained the GET and POST requests using pieces of source codes. Hopefully you
will be able to develop Java programs applying all the learnt elements.

70
References
Hughes.M, Shoffner.M, Hamner.D (1999), Java Network Programming- A Complete Guide
to Networking, Streams and Distributed Computing,Second Edition, Manning

Pitt.E (2006), Fundamental Networking in Java, Springer

71
BLANK PAGE
Unit 8 Using Protocol Handler

8.0 Introduction
In this unit we discuss the basic concept of how the non-supported protocol in URL class or
URLConnection can be implemented. Java allows addition of standard protocols through a few
URLStreamHandlerFactory and URLStreamHandler classes.

8.1 Objectives
At the end of this unit, you should be able to:
• explain protocol sequence in Java
• describe the way to add a standard protocol in Java class through protocol sequence

8.2 URL Protocol Chain


Most of the popular web browsers support other protocols apart from HTTP. The protocols are
FTP, gopher and specific protocols for particular applications. Most of these protocols are built
in the browser. This is one of the reasons that causes the browser available in today’s market
to have larger sizes and becoming slower when running applications.

To have a full understanding on how user can extend protocols in URL class, please test out
the example below:

Let us say a user tries to access a gif file from a web server using the URL address
http://x.y.z/images/logo.gif.

Firstly, the web browser needs to be connected to web server, browse through the information
header, decode the GIF image data and display it on the computer screen.

If the same problem happens in Java, it needs to get through two main chains:
(a) The first chain is based on the protocol, which is http, and getting input stream from
URL address object. The first chain can be accessed using URL classes,
URLStreamHandlerFactory, URLStreamHandler and URLConnection. URL address
objects address the object, which is the image to be downloaded. The getContent( )
method is called in URLStreamHandlerFactory to return URLStreamHandler object
that suits the protocol which is being used by URL. URLStreamHandler class is
responsible in creating URLConnection object that enables opening of input stream
channel for reading from URL address object. The flow of the first chain will be
explained in Figure 8.1.

72
Figure 8.1: URL protocol chain

The second chain control is based on the object type to be downloaded or the type of content.
Protocol chain identifies the object type and chooses the suitable decoder for the content type
of the particular URL. The decoder is responsible for reading the input stream protocol that is
being used to display the particular object.

Java uses URLConnection, ContentHandlerFactory and ContentHandler class to encode the


type of object content. Prior to that, URLConnection class must identify the type of content
for the URL address.

Then, it will call ContentHandlerFactory which returns the ContentHandler object to the
suitable content type and which is able to decode the content of the object. The flow of the
second chain will be explained in Figure 8.2.

73
Figure 8.2: URL content type sequence

Java supports extension of protocol using protocol handler which is also known as the stream
handler. This protocol handler is used to access the Web object by using a specific
application protocol as shown in URL object reference.

Protocol handler is implemented as a subclass of URLStreamHandler class. The subclass for


URLStreamHandler can override four methods of this class and there is one method that has
to be overridden, which is openConnection( ).

As explained in the previous unit, the openConnection( ) method returns the URLConnection
object from a certain protocol which is stacked in the URL class.
The URLConnection object can then be used to create the input and output stream and also to
access the source address by URL.

The parseURL( ) and setURL( ) methods are used to implement URL syntax parsing. The
toExternalForm( ) method is used to change the URL protocol type into a String object.

Website
To learn more about URLStreamHandler class, please browse through the web sites
http://download.java.net/jdk7/archive/b123/docs/api/java/net/URLStreamHandler.html
docstore.mik.ua/orelly/java/fclass/ch15_23.htm
www.geom.uiuc.edu/~addingto/docs/java_n12.htm

The purpose of a protocol handler is to execute the protocol defined by the user. The protocol
handler is not instantiated like the content handler. The method in URLConnection object
helps a lot in user defined protocol development. Each protocol is identified by the first
character until the symbol (:) in the URL. For example, the protocol for http://www.
myvista.zou.ac.zw, is http, and for foo://www. myvista.zou.ac.zw the protocol will be foo.

74
The protocol handler connects with the protocol through the URLStreamHandlerFactory
interface. Interface definition causes the execution of method in
createURLStreamHandlerFactory( ) in this class. This method will return the
URLStreamHandlerFactory object used in the user defined protocol.
The URLStreamHandlerFactory object is implemented using the static
setURLStreamHandlerFactory( ) method for the URL class.

Your Idea
Give two protocols that are supported by the java.net.URL or java.net.URLConnection class.

8.3 Protocol Handler Development


Development of protocol handler involves a few steps, such as:
(a) Execute the protocol handler by defining the subclass for URLStreamHandler
class. Example:

public class URLFooHandler extends URLStreamHandler

The openConnection( ) method in URLFooHandler class needs to be overridden to enable


access to user defined protocol in URL class. The openConnection( ) method will return
URLConnection object if successful. Example:

public class URLFooHandler extends URLStreamHandler {


public URLConnection openConnection(URL url)
throws IOException {
URL newURL = new
URL(“http://”+host+”/index.html”);
return newURL.openConnection( )
}

(b) Connect the protocol handler with defined protocol type using the
URLStreamHandlerFactory object. Example:

Class FooFactory implements URLStreamHandlerFactory.

URLStreamHandlerFactory class is an interface, thus the


createURLStreamHandlerFactory method has to be executed to return defined
protocol type. Example:

class FooFactory implements URLStreamHandlerFactory {


public FooFactory( ) {}
public URLStreamHandler createURLStreamHandler
(String protokol ) {
if(protokol.equals (“foo”) ) return new URLFooHandler( );
return null;
}

75
(c) The setURLStreamHandlerFactory( ) method of URL class is used to register
URLStreamHandlerFactory as a default URLStreamHandlerFactory which will be
used in defined protocol type. Example:

import java.io.*;
import java.net.*;
public class GetFooFactory {
public static void main(String args[]) {
try {
FooFactory foofactory = new FooFactory( );
URL.setURLStreamHandlerFactory(foofactory);
URL url = new URL(“foo://www. myvista.zou.ac.zw”);
InputStreamReader input = url.openStream( );
BufferedReader instream = new BufferedReader
(input);
String line = ””;
while ((line = in.readLine( )) != null)
System.out.println(line);
} catch (MalformedURLException e){}
}
}

Activity 8.1
Write a new protocol (daytime) that is able to display date and time from a server. Execute
the protocol on the URL class. Example to access URL time on server x.y.z is
daytime://x.y.z.

8.4 Summary
In this unit we exposed you to the basic concept of how the non-supported protocols in URL
or URLConnection class can be implemented. You are also able to add standard protocol
using a few URLStreamHandlerFactory and URLStreamHandler classes that are in Java.

76
References
Appa (2005), Content and protocol handlers,

CPAN Modules(2014), Protocols, Avialable from:


Https://perl.apache.org/docs/2.0/user/handlers/protocols.pdf, [12 December 2014]

Maso.B (2000), A New Era for Java Protocol Handlers , DevelopMentor

Puntambekar.A.A (2008), Internet Programming, First Edition , Technical Publications Pune

Reilly.D and Reilly.M (2002, Java Network Programming and Distributed Computing,
Addison-Wesley

77
Unit 9 Connecting to TCP Server

9.0 Introduction
In this unit we discuss the basic concept of a socket in network programming. To understand
this concept, you will learn about communication between clients and servers using the
existing applications in the Windows or UNIX operating system. The unit will end with an
explanation of how you can create a client using the Socket class.

9.1 Objectives
At the end of this unit, you should be able to:
• use the TELNET/HyperTerminal application in the operating system to gain
access to a server
• explain how the Socket class functions
• explain how to read and write data from and to a stream
• write a client application to access information from a server

9.2 Socket
Sockets are endpoints of the communication between 2 processes. Simply put, a socket allows
2 processes to communicate. Data from these processes are considered file descriptions that
enables data to be sent and received via the socket.

Data communication through the network uses various types of sockets:

(a) Stream Socket (TCP)


The stream socket is a connection-oriented facility whereby data can be sent without any record
limitations. If a connection between either of the processes terminates, both processes will be
informed accordingly.

(b) Datagram Socket (UDP)


The datagram socket is a connectionless transportation facility which is more efficient
compared to the TCP but is not reliable for communicating data. Data should be sent and
received as individual packets. For UDP, the data transfer is unreliable because the packets that
are sent are either lost, re-sent multiple times or received by the recipient in the incorrect order

(c) Raw Socket


The raw socket allows direct access to the lowest protocol layer in the network software. This
socket is used to control errors of the protocol codes.
Figure 9.1 gives us a view of communication between the server and the host.

78
Figure 9.1: An abstract view of communication between the web server and the host

9.3 Communication Domain


The socket designed should be generic and easily adaptable to any machine regardless of the
type of operating system used to transfer the data over the network. Sockets function within a
communication domain. This domain could exist either within a local system or a system on a
different network identifiable through its address. In UNIX, there are 2 supported
communication domains which are the intra-system and the intersystem communication.
(a) Intra-system communication (communication between 2 processes in the same
machine) exists in the UNIX domain only and uses the TLI (Transport Level
Interface) protocol.
(b) Intersystem communication in UNIX supports both the stream socket and the
datagram socket. The Intersystem communication can be done in a longer distance
and can happen in any machines connected to the Internet. The protocol executed
in intersystem is the TCP/IP protocol. As mentioned above, the intersystem
communication domain supports both the stream socket and the datagram socket.
The stream socket allows processes to communicate using TCP. When 2 sockets
are connected, data is written and read to and from this socket. The most used
applications that communicates via the TCP are:
• File Transfer Protocol (FTP)
• Simple Mail Transfer Protocol (SMTP)
• TELNET, connects to remote terminals

Figure 9.2 shows an abstract view of communication between a client and a server.

Figure 9.2: Abstract view of a socket communication

79
9.4 Client Socket Application

There are instances when you need to control a server which is online. Can this be done?
How?

Before programming our first network program, we will learn about the tools used to trace the
network, that is the Telnet. In Windows, operating system comes with an in-built Telnet
service. If you are not used to the application, you could lookup for the TELNET.EXE found
in the “\Windows” directory. If your machine does not have a Telnet application, you can
download the “HyperTerminal Private Edition” application as seen in Figure 9.3.

Figure 9.3: HyperTerminal Private Edition

To download the “HyperTerminal” application, you can go to:


http://www.hilgraeve.com/htpe/ or you could use the search engine to look for the installer.
Use the keyword “HyperTerminal” to run your search.
You may have experienced using the Telnet application to connect to a remote server to read
emails or run any maintenance job on the server. The Telnet application is popular amongst
hackers to investigate application types that are installed in a remote server:
The steps below will guide us to begin the Telnet application:
(a) Start Telnet
(b) Type in a host name that you are familiar with (vlsi.eng.ukm.my).
(c) Type in the port number used (13).

If you are using the command prompt to Telnet, type the following command:
telnet vlsi.eng.ukm.my 13

80
If you are using the HyperTerminal, follow the step below:
(a) Start HyperTerminal
(b) Click on File and choose New Connection
(c) Insert the connection information into the “Connection Description” dialog box.
(d) The “Connect To” dialog will be displayed. Choose TCP/IP in the “Connection Using”
field and insert the information as seen in Figure 9.3.

Figure 9.4: Connect to Dialog

The output produced by the steps above will be the date and time of the server. If you used
the command prompt, the output will be as seen in Figure 9.4 and if you used the
“HyperTerminal” the output will be as seen in Figure 9.5.

Figure 9.5: Telnet’s Command Prompt Output

81
Figure 9.6: HyperTerminal’s Output

What really happened? The command prompted the server for its time of day virtually which
is done by all UNIX servers. The time of day function is usually prompted at port 13. This port
number allows the application used to communicate between the client and the server.

Port 13 on the server will keep on querying the information until the application at that port is
terminated. If not, it will keep listening to the connection from the client. If there is a request
from a client, a connection between the 2 machines will be created.

Therefore, the server sends the date and time information to the client. After the server sends
the information, the connection between the two machines will be terminated. This means that
a connection will always exist unless it is terminated by either party.

When you begin the Telnet application with vlsi.eng.ukm.my at port 13, other parts of the
network will translate the host address into an IP address, which is in decimals such as
202.185.38.7. That network section will then send the request to connect to the directed server’s
port 13. Once that connection is made, the program on that server will respond and will revert
with the information and subsequently terminate the connection.

Apart from the above example, we can also use the Telnet for more interesting problems like
getting the source code of any given website. For this case, we will use the OUM website which
is www.oum.edu.my/html/index.php. Below are the steps to get the source code of the OUM
website using Telnet:

(a) Connect to www.oum.edu.my at port 80


(b) Without entering backspace, type the following :
GET /html/index.php / HTTP / 1.0
(c) Press ENTER twice.

82
Figure 9.7: Shows the output from the above command

Figure 9.7: The output from OUM website

Website

To know more about Telnet, you might want to visit the following sites:
(a) http://www.webopedia.com/TERM/T/Telnet.html
(b) http://www.networkuptime.com/archives/2000/10/introduction_to_1.html
(c) http://www.chicagotech.net/telnet.htm

When you access the OUM website above, you will find that the HTML text entitled index.php
which has already been formatted will be displayed. The command written above is the actual
command run by any web server in the world to access the OUM website.

Example 9.1 shows a network program which we will refer to when we discuss on how to write
a Telnet look-alike program in the Java language. The program will connect to a server at
particular port and print whatever that is responded by the server.

Before we analyse the main 2 lines, note that we need to import the java.net class.
Java.net is very important in Java when dealing with network access. Most classes needed for
network access are found in java.net package.

When reaching a remote server through the internet or the TCP/IP network, there might be
connection errors or other errors. The try/catch block will be used to catch those errors.
Example 9.1: Reading Streams from a Server
import java.io.*;
import java.net.*;
class MengujiSocket {
83
public static void main(String[] args) {
try {
Socket t = new Socket("vlsi.eng.ukm.my", 13);
DataInputStream is = new
DataInputStream(t.getInputStream( ));
boolean more = true;
while (more) {
String str = is.readLine( );
if (str = = null) more = false;
else
System.out.println(str);
}
}
catch(IOException e) { System.out.println("Error" + e);
}
}

The most crucial code of the program is found in these lines:

Socket t = new Socket("vlsi.eng.ukm.my", 13);


DataInputStream is = new DataInputStream(t.getInputStream( ));

The first line will start communication between the program and the network by opening the
socket connection which is an abstract class. In order for the socket to function, we also need
to provide the parameters host name and port number to the socket class’ constructor method.
If the host cannot be connected, the error UnknownHostException will be thrown to the calling
program.

Once the socket is open, the getInputStream method found in the java.net.Socket package will
return the InputStream object that will be used by most files to read input. Once the stream is
reached, all you need to do next is to read the stream from the program.

The following are the explanation for Example 9.1:


(a) Read all the characters sent by the server using the readLine( ) method; and
(b) Print all output lines received from the server

This process will repeat itself until the streams from the server completes or the server
terminates the connection. To ensure that there is no more streams sent by the server from the
method readLine( ), we can perform the following test:

if (str == null) ...

If the stream being sent by the server is NULL then it means that the stream is completed.

The Socket class in the above program is to establish a network connection.


It is a simple approach and is easily applied in Java. In the Socket class, Java conceals the
complexities of making a network connection.

When a connection has been made, Java sends the same interface to process the files. For
further information about the methods in the Socket class, you may refer to the “JavaTM 2

84
SDK, Standard Edition Documentation” for J2SDK 1.4. Below are a few methods used in the
program above and a short elaboration of their functions:

java.net.Socket
• Socket(String host, int port) throws UnknownHostException, IOException
Creates the socket and connects it to the mentioned port of a remote server

Parameter-parameter:
Host host name
port port number

• close( ) throws IOException


Closes the socket.

• InputStream getInputStream( ) throws IOException


Creates the input stream to read from the socket.

• public OutputStream getOutputStream( ) throws IOException


To return the output stream to be written into the socket.

Your Idea
Assume that you run the TCP client without starting the UDP server.
What is the impact and why?

Activity 9.1
To test your understanding, answer the questions below:

Write a client program that sends email via the SMTP service.
Note: a guide for using SMTP to send an e-mail
HELO <message>
MAIL FROM <e-mail sender>
RCP TO <e-mail recipient>
DATA < message>

9.5 Summary
The socket class represents the client socket and is a communication pathway between two
TCP communication ports owned by 1 or 2 machines. At the end of this unit, it is hoped that
you have understood the basic concept of Sockets in network programming. You have also
been introduced to the communication between client and server that uses the built-in
applications in the Windows or UNIX. Based on the examples given, you should now be able
to create a simple client using the Socket class.

85
References
Ciubotaru.B and Muntean.G.M (2013), Advanced Network Programming-Principles and
Techniques,Computer Communications and Networks, Springer-Velag London

Hughes.M, Shoffner.M, Hamner.D (1999), Java Network Programming- A Complete Guide


to Networking, Streams and Distributed Computing, Second Edition, Manning

Pitt.E (2006), Fundamental Networking in Java, Springer

Reilly.D and Reilly.M (2002), Java Network Programming and Distributed Computing,
Addison-Wesley

86
BLANK PAGE
Unit 10 Implementing TCP Server

10.0 Introduction
In this unit we discuss the basic concept of ServerSocket concept in network programming.
To understand this concept, you will be exposed to how servers apply the built-in application
that comes along with the operating system; Windows and UNIX. By the end of this unit, you
should be able to develop a simple server using the ServerSocket class.

10.1 Objectives
At the end of this unit, you should be able to:
• use the TELNET/HyperTerminal application in operating system to reach the server
• describe the functionality of the ServerSocket class
• discuss the approaches to read from and write to a stream
• explain how we create an application for a server that uses TCP protocol
• explain how to create a server using multithreads

10.2 A Simple TCP/IP Server

If you were given a website http://www.abc.com:80 which has a file named index.html. What
command will you use on the Telnet to view the source code of that file?

In unit 9, we have discussed how to connect to a remote server using the Java application. Let
us now venture into creating a server that can send information to the network. If you can recall
the previous unit, to ensure communication from a client to the server, the server needs an IP
address and a port number.

To build a server socket in Java, we need the ServerSocket. As an example, let us use port
number 9000 (a currently unused port number). To enable the server to be executed on that
port, we need the following command:

ServerSocket server = new ServerSocket(9000);

The above instruction tells the server to start monitoring port number 9000. The command
below, on the other hand:

Socket socket = server.accept( );

will instruct the Java programme to wait for an infinite amount of time until the client is
connected to that port. If there is any request incoming from the client, the accept( ) method
will be executed automatically by Java. It will return the Socket object.

We can use this object to get input streams and output streams from the same socket, as coded
below:
DataInputStream in = new DataInputStream(socket.getInputStream( ));
PrintStream out = new PrintStream(socket.getOutputStream( ));

87
The first statement of the code above instructs the server to accept information sent to it as
input. Therefore, it functions as a reader for any data sent by the client.

The second statement permits the server to send any data to the client. For both cases to be
executed successfully, a connection between them using a socket needs to exist.

From the instructions above, we can develop a server that can send the message “Hello” to the
client that connects to it. And when the ENTER key is pressed, the connection between the
client and server will be terminated.

Here are the steps to develop a server:


(a) Create a server for a port i.e. port 9000

ServerSocket server = new ServerSocket(9000);

(b) Permits the server to receive requests from the client

Socket socket= server.accept( );


(c) Instructs to send the message “Hello” to the client.

PrintStream out = new PrintStream(socket.getOutputStream( ));


out.println( “Hello !Press ENTER to exit.”);

(d) Reads ENTER key.

DataInputStream in=new DataInputStream(socket.getInputStream( ));


String str = in.readLine( );

(e) Close the socket connection


socket.close( )

The complete program can be seen at Example 10.1.


Example 10.1: Sending Messages from the Server to the Client.

import java.io.*;
import java.net.*;
class ServerHello {
public static void main(String[] args) {
try {
ServerSocket server= new ServerSocket(9000);
Socket socket = server.accept( );
DataInputStream in = new
DataInputStream(socket.getInputStream( ));
PrintStream out = new
PrintStream(socket.getOutputStream( ));
out.println(“Hello !Press ENTER to exit”);
String str = in.readLine( );
String str = in.readLine( );
socket.close( );
}

88
catch(IOException e) { System.out.println("Error" + e);
}
}

To test out the program above, you will need to compile and run the program.
After that, use the Telnet of the HyperTerminal to connect to the server and port as shown
below:

Server : 127.0.0.1
Port : 900

The IP address 127.0.0.1 is a specific address to A class. It is also known as the local loop
back address, which refers to local computer.

We must know the IP address of the computer that runs the programme to reach a server. The
get the actual IP address, you can use this command line:

• If you are using Windows 2000/NT, type:


ipconfig
• If you are using UNIX, type:
ifconfig –a

When you connect to the server using Telnet, you will receive the following message:
Hello! Press ENTER to exit.
on your Telnet screen. When you press the ENTER key, the server will terminate the
connection to your machine. Refer to Figures 10.1, 10.2, 10.3 and 10.4.

Below is a screen shot showing the process of connecting to the server IP address 127.0.0.1 at
port 9000 using the Telnet application

Figure 10.1: Using TELNET to connect to the Server

The following is the output as displayed on your screen. The message Connection to host lost
will be displayed once the ENTER key is pressed.

Figure 10.2: Connection terminates when the ENTER key is pressed

89
The below screen shot shows the connection process using the HyperTerminal
application.

Figure 10.3: Connecting to the Server with the HyperTerminal

The output screen below displays the message from the server. Take note that the
status bar displays the message Disconnected when the ENTER key is pressed.

Figure 10.4: Disconnected message appears when ENTER is pressed

10.3 Case Study Client/Server Connections using Socket/Socket Server


In unit 9, you were shown ways to connect to a server. In this unit, we discuss ways to send
data from a client to the server using SocketServer. This section summarises all the important
concepts in unit 9 and unit 10.

To start a TCP session both the client and server are needed. We will see a sample program
that shows us how we can use Java to connect the client to the server. Firstly, the server needs
to be set up to listen to an assigned port. When a connection is established from a client to the
server, the client and server will have an instance of the Socket class. This will create an input
and output stream by which all communication can happen.

90
Example 10.2: Server Program (Server.java).

import java.lang.*;
import java.io.*;
import java.net.*;
class Server {
public static void main(String args[]) {
String data = "OUM ialah universiti terulung di Malaysia";
try {
ServerSocket srvr = new ServerSocket(1234);
Socket skt = srvr.accept( );
System.out.print("Pelayan telah disambungkan\n");
PrintWriter out = new PrintWriter(skt.getOutputStream( ),
true);
System.out.print("Menghantar data ke Klien.....\n");
out.print(data);
out.close( );
skt.close( );
srvr.close( );
}
catch(Exception e) {
System.out.print("Ralat Sambungan\n");
}
}
}

Example 10.3: Client Program (Client.java).

import java.lang.*;
import java.io.*;
import java.net.*;
class Client {
public static void main(String args[]) {
try {
Socket skt = new Socket("localhost", 1234);
BufferedReader in = new BufferedReader(new
InputStreamReader(skt.getInputStream( )));
System.out.print("Data dari pelayan: ");
while (!in.ready( )) {}
System.out.println(in.readLine( ));
System.out.print("'\n");
in.close( );
}
catch(Exception e) {
System.out.print("Ralat Sambungan\n");
}
}
}

The examples above use localhost, which means the machine’s IP address is

91
127.0.0.1. With this approach, both the server and the client run in the same computer.

Type out both the programs above and execute the Server.java programme using the
command lines below:
javac Server.java
java Server
Next, open a new command line and execute the Client.java programme with the following
instructions:
javac Client.java
java Client
The output below will be displayed:

Figure 10.5: Server Program Output

Activity 10.1
To test you understanding, answer these questions:

(a) The Server.java and Client.java use the same port number that is 1234. What will
happen if the programmes use different port numbers?
(b) Both programmes were executed in localhost. What changes need to be made so that
they can be executed on two different machines on the same network?
(c) What will happen if the Client.java programme was executed before Server.java?
Justify your answer.

10.3 Multithreaded Server

In most situations, the server receives requests from more than 1 client.
How does a server manage each of the requests?

The previous server program has a downfall which is in handling multiple and simultaneous
requests. As an example, the server will need to be listening all the time and; while the clients
will be making requests simultaneously down to the very same second. The server application
might need to be running continually at server computer, and clients from all Internet locations
could be using the same server at the same time.

The program in example 10.1 monopolises the server at the same time.

92
Please take note that each time the server accepts a request and the accept( ) method will be
called and return the Socket object. To create a multithread server, this problem needs to be
overcome so that the server can serve many clients. One of the more popular solutions would
be to use the Thread class.

Every time a connection is made, the server program will throw a new thread to maintain a
constant connection between that client and the server. After that, the main server programme
will then return to listening for new requests.

An extract of the code (seen below) will better explain how the server can service many clients
whilst still listening for more client requests.

while(true) {
Socket = server.accept( );
Thread = new ServerThread(socket);
thread.start( );
}

The ServerThread will be inherited from the main Thread class and this will cancel off the run(
) method that ensures a continuous connection.

import java.io.*;
import java.net.*;
public class ServerThread extends Thread {
private Socket socket;
public ServerThread (Socket i) {
socket = i;
}
public void run( ) {
try {
DataInputStream in = new
DataInputStream(socket.getInputStream( ));
PrintStream out = new
PrintStream(socket.getOutputStream( ));
out.println("Hello!Tekan ENTER untuk keluar.\r");
String str = in.readLine( );
socket.close( );

The program above ensures that each connection starts with a new thread, allowing multiple
clients to be connected to the same port simultaneously. Test the program on the server by
compiling and executing it. Next, open a few Telnet applications and start connecting to the
server simultaneously or sequentially.
You will find that the server will not terminate unless the program is stopped manually.

Your Idea
Will it be appropriate to use the multithread approach to manage multiple clients
simultaneously on a UDP server? If yes, how is it done? If no, justify the reasons.

93
Activity 10.2
To test your understanding, answer these questions:
(a) Write a client programme that replaces Telnet application. Hint: Refer to Unit 9.
(b) Create a server that provides day-time service as in Unit 9.

10.5 Summary
Java offers a very good support for TCP socket in the form of two socket class namely,
java.net.Socket and java.net.ServerSocket. in this unit we discussed the basic concept of
ServerSocket in network programming. ServerSocket class should be used when creating
server software connected to a local port.

To further understand the concept, you were exposed to how a server created functions using
the built-in application in the operating systems (Windows/UNIX). You were also taught
about how to create a simple server using the ServerSocket class.

94
References
Calvert.K.L and Donahoo.M.J (2008), TCP/IP Sockets in Java Practical Guide for
Programmers, Second Edition, Elsevier

Graba.J (2013), An Introduction to Network Programming with Java-Java 7 Compatible,


Third Edition, Springer

Pitt.E (2006), Fundamental Networking in Java, Springer

95

You might also like