BITH261 Network Programming
BITH261 Network Programming
Technology
Network Programming
Module BITH261
Adapted By: Zano Collen
GradCE (UZ)
BA Gen(Hons)(UZ)
ii
Published by: The Zimbabwe Open University
Mount Pleasant
Harare, ZIMBABWE
Year: 2017
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
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.
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.
Course Synopsis
This course is divided into ten units. The following are the synopses for each unit:
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 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.
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
Additional References
David. R.& Michael. R (2002). Java Network Programming and Distributed Computing.
Boston: Addison Wesley.
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:
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
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).
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.
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
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.
(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.
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.
4
Table 1.2: Java Categories
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.
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.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.
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.
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.
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 {
// 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?
(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
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.
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.
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.
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.
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.
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.
15
Figure 2.5: IP network support among the physical networks
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:
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.
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.
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
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:
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.
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
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.
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.
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
System.out.write(data);
data = fileInput.read( );
(d) Close
fileInput.close( );
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( );
}
}
f0.write(buf[i]);
f0.write(buf[i]);
f1.write(buf);
(e) Close
f1.close( );
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.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);
}
}
InputStream input=System.in;
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.
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
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.
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.
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.
Activity 4.1
Answer questions below to test your understanding.
34
4.3 Multithreading
Figure 4.1: Application process that manages more than one subprocess
35
thread1.start( );
thread2.start( );
}
}
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:
(c) Create Temporary Variable from the Generated Class so that it is Easier to Manipulate
(d) Create Temporary Variable from Thread Class and Send Temporary Variable to Thread
Class Constructor
t.start ( );
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.
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( );
}
}
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 “); }
.
.
.
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.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.
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:
And
42
countValue=count;
}
public synchronised int getCount( ) {
return countValue;
}
}
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?
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.
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.
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.
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.
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,
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
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?
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:
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.
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
• 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
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:
Apart from that, we can also create the URL object from a relative URL address.
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:
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:
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:
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.
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( ));
}
}
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?
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.
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
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
...}
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]
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
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.
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.
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( );
}
}
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:
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.
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.
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.
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 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:
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
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
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.
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
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:
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.
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.
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);
}
}
}
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
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?
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){}
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
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
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.
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.
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.
(b) Connect the protocol handler with defined protocol type using the
URLStreamHandlerFactory object. Example:
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,
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.
78
Figure 9.1: An abstract view of communication between the web server and the host
Figure 9.2 shows an abstract view of communication between a client and a server.
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.
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.
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.
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:
82
Figure 9.7: Shows the output from the above command
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 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.
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 the stream being sent by the server is NULL then it means that the stream is completed.
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
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
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
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:
The above instruction tells the server to start monitoring port number 9000. The command
below, on the other hand:
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.
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:
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
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.
89
The below screen shot shows the connection process using the HyperTerminal
application.
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.
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");
}
}
}
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:
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.
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
95