Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 21

Name: __________________________ Course & year: _____________ Date of Submission: ____________

Course Code: IT 211 Descriptive Title: Integrative Programming and Technologies

Lesson 2. DCOM,CORBA,RMI

INTRODUCTION
In this lesson, you will learn the basic elements and concepts of Java programming language. As you
begin to learn Java, you must always be aware of the type of data that your program is processing. The
programs in this section process strings of characters, many of the programs in this section process numbers,
and we consider numerous other types later in the learning material.

Learning Objectives:
At the end of this lesson, you will be able to:
1. discuss some tools used in the development of distributed applications(RMI,DCOM,CORBA);
2. differentiate RMI, DCOM, CORBA; and
3. evaluate how distributed systems are managed.

LESSON PROPER

Distributed object computing is gaining a lot of importance in today’s computing world. An important
characteristic of large computer networks such as the Internet or large corporate intranets is that they are
heterogeneous. Distributed object computing methodologies aim to allow application interoperability and
independence of platform, operating system, programming language and even of network and protocol.
With the advent of the Internet (and other network technologies), there is a wide spread utilization of
object technologies. Object oriented paradigms are increasingly getting employed in distributed environments.
The use of object technologies in distributed systems gives rise to some key issues like sharing address space,
sharing object, etc. In a distributed object system, each of these distributed object components interoperate as a
unified whole.
These objects may be distributed on different computers throughout a network, living within their own
address space outside of an application, and yet appear as though they were local to an application.
Three of the most popular distributed object paradigms are Microsoft's Distributed Component Object Model
(DCOM), OMG's Common Object Request Broker Architecture (CORBA) and JavaSoft's Java/Remote
Method Invocation (Java/RMI). In this article, let us examine the differences between these three models from
a programmer's standpoint and an architectural standpoint. At the end of this article, you will be able to better
appreciate the merits and innards of each of the distributed object paradigms.

CORBA

CORBA is based on the Request-Response architecture. There is an object implementation on the


server, which the client requests to execute. The client and the server object implementation do not have any
restrictions on the address space, for example the client and the server can exist in the same address space, or
can be located in separate address spaces on the same node, or can be located on separate nodes altogether.
CORBA objects are essentially object that supports the CORBA:: Object IDL interface and the Remote
references are called Object References. There is a specification of the CORBA IDL Language and how it is
mapped with other languages. It essentia lly provides a means for the interface definitions. The Proxy or a local
representative for the client side is called the IDL stub; the server-side proxy is the IDL skeleton. The proxy
represents an object created on the client side, which is used for more functionality like support for Dynamic
invocation. For Marshalling the request and the response, the information is delivered in a canonical format
defined by the IIOP protocol used for CORBA interoperability on the Internet. IDL stub makes use of dynamic
invocation interface for marshalling on the client side. Similarly on the server side, IDL Skeletons use the
Dynamic Skeleton Interface for unmarshalling the information. The request (response) can also contain Object
Reference as parameters; remote object can be passed by reference.

Fig 1 shows the CORBA architecture, which follows a Broker pattern [1]. The ORB is used for
connecting the client and the server and it acts as a broker object. The IDL stub along with DII stub performs the
client side proxy and the POA IDL skeleton (along with the DSI skeleton used for dynamic delivery) does the
Server-Side proxy. Many CORBA implementations use a direct communication between the client stubs and the
Server Skeleton. The Interface Repository is used for introspection (particularly in case of a dynamic invocation
and dynamic delivery). The Implementation Repository is used for reactivation of servers.

1
Providing and
employing a service For
registering a service (object)
with the broker, CORBA uses
the Object Adapter POA which
provides methods like activate_
object(), activate(). CORBA
makes use of the CORBA
Naming Service for providing
name spaces and for mappings
among the Object References
and names. Object References
can be obtained by a client in
two ways: first, the client can
ask the naming service to
resolve a known name into a
corresponding Object
Reference; second, the client can also ask the CORBA trading service to provide a list of services (Object
References) that have the properties used as the search key. The client then bounds to the server once it
obtains the object reference for the implementation. The client can use two types of invocations as:

1. Static invocation and delivery: For static invocation the client is compiled with the knowledge service IDL
specification. Here the proxy implements the mapped IDL interface methods with the corresponding code of the
proxy being encapsulated in the IDL stub. In the same manner the IDL skeleton is the code of the server-side
proxy. This implements the static delivery.
2. Dynamic invocation and delivery: For dynamic invocations, a Request object is returned by calling the
create_request() method in the proxy. There is also a way to submit arguments with the request. For getting
information about the target interface the Interface Repository acan be consulted. The actual dynamic invocation
is initiated by calling invoke(), a method of the Request object. As far as dynamic delivery is concerned, the
server-side proxy contains the Dynamic Skeleton code which delivers the request via the invoke() method
supported by the PortableServer:: DynamicImplementation interface.

CORBA allows for combining static invocation at the client side with dynamic delivery at the server side
and vice versa. At the server side, the choice between static and dynamic delivery is made by the server object
itself (it can be determined, e. g., as a part of the registration with POA), regardless of the way a request was
created, i. e., via a dynamic or static invocation. A halfway between static and dynamic invocation is dynamic
downloading of stubs which can be applied in CORBA clients implemented in Java. In this case, the client code
can be compiled without employing the IDL compiler (just the knowledge about the interface form will do).

STEPS in deploying the CORBA application

STEP 1: Defining object interfaces-The first step in creating an application is to specify is to specify all of your
objects and their interfaces using the OMG's Interface Definition Language (IDL). Writing the StockMarket
interface in IDL: The StockMarket interface provides a single method get_price() for obtaining the current value
of the stock.
STEP 2: Generating client stubs and server servants Use IDL compiler(idl2java) to generate: · Client Stub Code
· Server Skeleton Code
STEP 3: Write the client
STEP 4: Write the server object implementation code
STEP 5: Compile the client and server code vbjc –d classes StockMarketClient.java vbjc –d classes
<directory_for_classes> StockMarketServer.java
STEP 6: Start the Visibroker Smart Agent osagent -c
STEP 7: Start the server (vbj StockMarketServer or java StockMarketServer) STEP 8: Run the client
application(vbj StockMarketClient or java StockMarketClient)

Benefits of CORBA

 Programming-language independent interface. ·


 Legacy integration
 Rich distributed object infrastructure.
 Location transparency. ·
 Network transparency ·
 Direct object communication.
 Dynamic Invocation Interface

2
JAVA RMI

This is a brief introduction to Java Remote Method Invocation (RMI). Java RMI is a mechanism that allows one
to invoke a method on an object that exists in another address space. The other address space could be on the
same machine or a different one. The RMI mechanism is basically an object-oriented RPC mechanism.

Java/RMI relies on a
protocol called the Java
Remote Method Protocol
(JRMP). Java relies heavily on
Java Object Seria lization,
which allows objects to be
marshaled (or transmitted) as
a stream. Since Java Object
Serialization is specific to
Java, both the Java/RMI
server object and the client
object have to be written in
Java. Each Java/RMI Server
object defines an interface, which can be used to access the server object outside of the current Java Virtual
Machine (JVM) and on another machine's JVM. The interface exposes a set of methods, which are indicative of
the services offered by the server object. For a client to locate a server object for the first time, RMI depends on
a naming mechanism called an RMIRegistry that runs on the Server machine and holds information about
available Server Objects. A Java/RMI client acquires an object reference to a Java/RMI server obje ct by doing a
lookup for a Server Object reference and invokes methods on the Server Object as if the Java/RMI server object
resided in the client's address space. Java/RMI server objects are named using URLs and for a client to acquire
a server object reference, it should specify the URL of the server object as you would with the URL to a HTML
page. Since Java/RMI relies on Java, it can be used on diverse operating system platforms from mainframes to
UNIX boxes to Windows machines to handheld devices as long as there is a Java Virtual Machine (JVM)
implementation for that platform.

Advantages of RMI

 Support seamless remote invocation on objects in different virtual machines.


 Support callbacks from servers to applets. · Integrate the distributed object model into the Java
language in a natural way while retaining most of the Java language's object semantics.
 Make differences between the distributed object model and local Java object model apparent.
 Make writing reliable distributed applications as simple as possible.
 Preserve the safety provided by the Java runtime environment.
 Single language.
 Free.
DCOM

DCOM is the
distributed extension to COM
(Component Object Model)
that builds an object remote
procedure call (ORPC) layer
on top of DCE RPC to
support remote objects. COM
is an component based
development model for
Windows environment. A
component is a reusable
piece of software in binary
form (as opposed to source
code), that can be plugged into other components from other vendors with little effort. COM has its roots in OLE
(Object Linking and Embedding), shipped with Windows 3.1. The idea of OLE was to provide an improved
mechanism for dealing with compound documents and enabling things like smart documents that could embed
or link Excel spreadsheet into a word document. OLE is mainly a library of predefined interfaces and default
implementation of some of them. Over the years, OLE faded into background and with the release of Windows
NT 4.0 in 1996, COM took center stage. COM supports component interaction on local machine, both in one
address space (process) and across separate address spaces. DCOM provides the same functionality but
across machines over a network
Architectural Overview The COM server is the program that implements COM interfaces and classes.
COM Servers come in three basic configurations · In-process, or DLL servers · Stand-alone EXE servers ·
Windows NT based services

3
Benefits of DCOM

 Large User Base and Component Market


 Binary Software Integration - Large-scale software reuse (no source code) - Cross-language software
reuse.
 On-line software update. - Allows updating a component in an application without recompilation,
relinking or even restarting.
 Multiple interfaces per object · Wide selection of programming tools available, most of which provide
automation of standardcode.

CORBA, RMI, and DCOM

We try to compare CORBA, RMI, and DCOM from different perspectives. Table 1 shows some basic component
comparison results among the three.

CORBA RMI DCOM


Object Diverse languages can Only Java language can be Specification is at the binary
Implementation be used as long as the applied, because the Java level. Diverse languages like C+
IDL can be mapped to Object Serialization usage. +, Java, Delphi, and even
that language. COBOL can be used.
Client/Server The client stub is The client stub is called The client stub is called a proxy,
Interface called a stub, and the a stub, and the server side and the server side is
server side is skeleton. is skeleton. called stub.
Remote Internet Inter-ORB Java Remote Method Object Remote Procedure
Protocol Protocol (IIOP) Protocol (JRMP) Call (ORPC)
Object Object A remote server object is Interface
Identification references (objref) are assigned with an ObjID as pointer is used
used as the object its identification. as a unique
handle at run-time. identifier for a
remote server
object.
Object The ORB is used to The object location and Use the Service Control
Location locate an object, activation are on Java Manager (SCM) to locate and
and and Object Adapter is Virtual Machine (JVM) activate an object.
Activation used for activation.
Inheritance Support multiple Support multiple inheritance Supports multiple interfaces for
inheritance at the at the interface level. Every objects. Every object
interface level. Every object implements IUnknown.
interface inherits implements java.rmi.Remot
from CORBA.Object e
On- . A client can bind to a A client can do A client can do
demand naming or a trader a lookup() on the remote a CoCreateInstance() to activate
Activation service to activate a server object�s URL name a server object.
server object by to obtain the object
obtaining a server reference.
reference
Exception Exceptions are thrown Exceptions are thrown at the Exceptions are thrown out
Handle at the interface interface definition. to HRESULT to be handled. For
definition. Exception Exceptions are serialized richer exception handling, it
handling is taken care and marshaled back across uses Error Objects,
of by Exception the wire. and ISupportErrorInfo interface
Objects. has to be implemented.
Garbage . . Does not attempt to Attempts to perform Attempts to perform distributed
Collection perform general distributed garbage garbage collection on the wire
purpose distributed collection of remote server by pinging. The DCOM wire
garbage collection objects using the protocol uses a Pinging
mechanisms bundled in the mechanism to garbage collect
JVM. remote server object references

Table 2:  CORBA, RMI, and DCOM comparison table

 Table 1 remarks: Unlike CORBA and RMI, which support multiple inheritance at the interface level, DCOM
supports multiple interfaces for objects and uses the QueryInterface() method to navigate among interfaces.
This means that a client proxy dynamically loads multiple server stubs in the remote layer depending on the
number of interfaces being used. RMI relies heavily on Java Object Serialization, which requires objects to be

4
coded using Java. DCOM and CORBA are relative more portable in object implementations. Both RMI and
DCOM try to perform distributed garbage collection. RMI takes the advantage of the mechanisms bundled in
JVM, and DCOM uses a Pinging mechanism to garbage collect remote server object references. Finally, in
terms of usability, RMI can be run at any platform as long as the JVM implementation is there; DCOM requires a
COM Service implemented platform; and CORBA can be implemented if a CORBA ORB exists.

An implementation example is provided in [8], which uses Java to implement a stock price query system
(client/server) using the three models. Each of the implementations defines an IStockMarket interface and
a get_price() method that returns a float value indicating the stock value of the symbol passed in. The example
gives some inside look from practical point of view.

Lesson 3. MIDDLEWARE AND WEB SERVICES

INTRODUCTION

The natural evolution of computing technologies has brought us object-oriented programming,


component based programming, middleware, and now Web services (WSs). For the obvious reason that
software components and middleware are the technologies predominantly used in the computing world
nowadays.

Learning Objectives:

At the end of this lesson, you are able to:

1. define Web services and middleware;


2. describe how web services are used to integrate disparate applications in an organization: for example,
describe the role of the WSDL, SOAP, and UDDI architectures in creating and using web services; and
3. differentiate Middleware from Web services;

LESSON PROPER

o WEB SERVICES
Different books and different organizations provide different definitions to Web Services. Some of them are
listed here.
 A web service is any piece of software that makes itself available over the internet and uses a
standardized XML messaging system. XML is used to encode all communications to a web service.
For example, a client invokes a web service by sending an XML message, then waits for a
corresponding XML response. As all communication is in XML, web services are not tied to any one
operating system or programming language—Java can talk with Perl; Windows applications can talk
with Unix applications.
 Web services are self-contained, modular, distributed, dynamic applications that can be described,
published, located, or invoked over the network to create products, processes, and supply chains.
These applications can be local, distributed, or web-based. Web services are built on top of open
standards such as TCP/IP, HTTP, Java, HTML, and XML.
 Web services are XML-based information exchange systems that use the Internet for direct application-
to-application interaction. These systems can include programs, objects, messages, or documents.
 A web service is a collection of open protocols and standards used for exchanging data between
applications or systems. Software applications written in various programming languages and running
on various platforms can use web services to exchange data over computer networks like the Internet
in a manner similar to inter-process communication on a single computer. This interoperability (e.g.,
between Java and Python, or Windows and Linux applications) is due to the use of open standards.
To summarize, a complete web service is, therefore, any service that −
 Is available over the Internet or private (intranet) networks
 Uses a standardized XML messaging system
 Is not tied to any one operating system or programming language
 Is self-describing via a common XML grammar
 Is discoverable via a simple find mechanism

o Components of Web Services


The basic web services platform is XML + HTTP. All the standard web services work using the following
components −
 SOAP (Simple Object Access Protocol)

5
 UDDI (Universal Description, Discovery and Integration)
 WSDL (Web Services Description Language)

o How Does a Web Service Work?


A web service enables communication among various applications by using open standards such as HTML,
XML, WSDL, and SOAP. A web service takes the help of −
 XML to tag the data
 SOAP to transfer a message
 WSDL to describe the availability of service.
You can build a Java-based web service on Solaris that is accessible from your Visual Basic program that runs
on Windows.
You can also use C# to build new web services on Windows that can be invoked from your web application that
is based on JavaServer Pages (JSP) and runs on Linux.

Example
Consider a simple account-management and order processing system. The accounting personnel use a client
application built with Visual Basic or JSP to create new accounts and enter new customer orders.
The processing logic for this system is written in Java and resides on a Solaris machine, which also interacts
with a database to store information.
The steps to perform this operation are as follows −
 The client program bundles the account registration information into a SOAP message.
 This SOAP message is sent to the web service as the body of an HTTP POST request.
 The web service unpacks the SOAP request and converts it into a command that the application can
understand.
 The application processes the information as required and responds with a new unique account number
for that customer.
 Next, the web service packages the response into another SOAP message, which it sends back to the
client program in response to its HTTP request.
 The client program unpacks the SOAP message to obtain the results of the account registration
process.

o MIDDLEWARE
Today, most business processes have become digitalized, and most organizations have very diverse
digital needs.

To fulfill these needs, businesses have to use many different hardware and software products.

Most of these hardware and software were designed separately. They were not necessarily built to work
together. At the same time, organizations need these different hardware and software to work together in order
to make digital processes more efficient.

Problem is, how do you make them work harmoniously when they weren’t built to work together?
This is where middleware comes in.
There are usually two levels on any device.

The first one is the operating system, which is the low level software whose main role is to manage the
device’s resources and control the device’s basic functions.

The second level is the applications that are meant to run on top of the operating system.

These applications expand the functions of the device beyond what is offered by the operating system.

Middleware refers to any behind the scenes software that allows these two levels to communicate and
interact with each other.

For instance, middleware will sit between Windows 10 and an office productivity suite.

Aside from the operating system and applications, middleware also helps separate process, applications
and software components to exchange information either within the same device, or between multiple devices.

You can compare middleware to a translator helping people who speak different languages understand
each other.

6
In this case, middleware facilitates interoperability between applications running on different frameworks.
Middleware does this by providing a standard-based means of data exchange.

This way, the two applications can connect without having to communicate directly.

Some people refer to middleware as plumbing since it connects and passes data between two fundamentally
different applications.

Middleware has also been referred to as “software glue”, since it helps “glue” together different software so they
can work together.

The term middleware is a bit vague since it does not refer to a specific type of software. Instead, it refers to any
software that sits between and links two separate applications.

Middleware includes software like content management systems,  application servers,  web servers, and other
similar tools that support the development and delivery of applications. Middleware started becoming popular in
the 80s as a solution for enabling newer applications to work on older systems.

To enable communication between different applications, middleware utilizes different communication


frameworks such as Representational State Transfer (REST), web services,  JavaScript Object Notation
(JSON),  Simple Object Access Protocol (SOAP), and so on.

Modern integration infrastructure such as enterprise service bus (ESB) and API management software also
depend on middleware concepts.

LESSON 4. Network Programming

INTRODUCTION

This lesson explains how to connect your JAVA application to a network. You will learn how to read files
from over the internet as well as have two or more programs communicate with one another over a network
connection (wired or wireless). You will learn about Uniform Resource Locators as well as Client/Server
communications using TCP and Datagram Sockets.

Learning Objectives:

At the end of this lesson, you will be able to:

1. acquire basic knowledge about Uniform Locators, Client/Server communications using TCP and
Datagram Socket.
2. Apply the client‐server model in networking applications. 

LESSON PROPER

Network Programming involves writing programs that communicate with other programs across a
computer network.

There are many issues that arise when doing network programming which do not appear when doing
single program applications. However, JAVA makes networking applications simple due to the easy-to-use
libraries. In general, applications that have components running on different machines are known as distributed
applications ... and usually they consist of client/server relationships.

A server is an application that provides a "service" to various clients who request the service.

There are many client/server scenarios in real life:


 Bank tellers (server) provide a service for the account owners (client)
 Waitresses (server) provide a service for customers (client)
 Travel agents (server) provide a service for people wishing to go on vacation (client)

In some cases, servers themselves may become clients at various times.

 E.g., travel agents will become clients when they phone the airline to make a
reservation or contact a hotel to book a room.

In the general networking scenario, everybody can either be a client or a server at any time. This is known as
peer-to-peer computing. In terms of writing java applications it is similar to having many applications
communicating among one another.

7
 E.g., the original Napster worked this way. Thousands of people all acted as clients (trying to download
songs from another person) as well as servers (in that they allowed others to download their songs).

There are many different strategies for allowing communication between applications. JAVA technology allows:

 internet clients to connect to servlets or back-end business systems (or databases).  applications to
connect to one another using sockets.
 applications to connect to one another using RMI (remote method invocation).
 Some others

We will look at the simplest strategy of connecting applications using sockets.

A Protocol is a standard pattern of exchanging information.

It is like a set of rules/steps for communication. The simplest


example of a protocol is a phone conversation:

1. JIM dials a phone number


2. MARY says "Hello..."
3. JIM says "Hello..."
4. ... the conversation goes on for a while ...
5. JIM says "Goodbye"
6. MARY says "Goodbye"

Perhaps another person gets involved:

1. JIM dials a phone number


2. MARY says "Hello..."
3. JIM says "Hello" and perhaps asks to speak to FRED
4. MARY says "Just a minute"
5. FRED says "Hello..."
6. JIM says "Hello..."
7. ... the conversation goes on for a while ...
8. JIM says "Goodbye"
9. FRED says "Goodbye"

Either way, there is an "expected" set of steps or responses


involved during the initiation and conclusion of the
conversation. If these steps are not followed, confusion
occurs (like when you phone someone and they pick up the phone but do not say anything).

Computer protocols are similar in that a certain amount of "handshaking" goes on to establish a valid connection
between two machines. Just as we know that there are different ways to shake hands, there are also different
protocols. There are actually layered levels of protocols in that some low level layers deal with how to transfer
the data bits, others deal with more higher-level issues such as "where to send the data to".

Computers running on the internet typically use one of the following high-level Application Layer protocols to
allow applications to communicate:

o Hyper Text Transfer Protocol (HTTP)


o File Transfer Protocol (FTP)
o Telnet

This is analogous to having multiple strategies for communicating with someone (in person, by phone,
through electronic means, by post office mail etc...).

In a lower Transport Layer of communication, there is a separate protocol which is used to determine
how the data is to be transported from one machine to another:

o Transport Control Protocol (TCP)


o User Datagram Protocol (UDP)

This is analogous to having multiple ways of actually delivering a package to someone (Email, Fax, UPS, Fed-
Ex etc...)
Beneath that layer is a Network Layer for determining how to locate destinations for the data (i.e., address). And
at the lowest level (for computers) there is a Link Layer which actually handles the transferring of bits/bytes.

8
So, internet communication is built of several layers:

When you write JAVA


applications that communicate over a network, you are programming in the Application Layer.

JAVA allows two types of communication via two main types of Transport Layer protocols:

Why would anyone want to use UDP protocol if information may get lost ? Well, why do we use email or the post
office ? We are never guaranteed that our mail will make it to the person that we send it to, yet we still rely on
those delivery services. It may still be quicker than trying to contact a person via phone to convey the data (i.e.,
like a TCP protocol).

One more important definition we need to understand is that of a port:

9
A port is used as a gateway or "entry point" into an application

Although a computer usually has a single physical connection to the network, data sent by different
applications or delivered to them do so through the use of ports configured on the same physical network
connection. When data is to be transmitted over the internet to an application, it requires that we specify the
address of the destination computer as well as the application's port number. A computer's address is a 32-bit IP
address. The port number is a 16-bit number ranging from 0 to 65,535, with ports 0-1023 restricted by well-
known applications like HTTP and FTP.

o Reading Files From the Internet (URLs)

A Uniform Resource Locator (i.e., URL) is a reference (or address) to a resource over a network (e.g., on the
Internet).

So, a URL can be used to represent the "location" of a webpage or web-based application. A URL is really just a
String that represents the name of a resource ... which can be files, databases, applications, etc.. A resource
name consists of a host machine name, filename, port number, and other information. It may also specify a
protocol identifier (e.g., http, ftp) Here are some examples of URLs:

http://www.cnn.com/
http://www.apple.com/ipad/index.html
http://en.wikipedia.org/wiki/Computer_science
Here, http:// is the protocol identifier which indicates the protocol that will be used to obtain the resource. The
remaining part is the resource name, and its format depends on the protocol used to access it.

A URL resource name may generally contain:

 a Host Name - The name of the machine on which the resource lives.
http://www.apple.com:80/ipad/index.html
 a Port # (optional) - The port number to which to connect.
http://www.apple.com:80/ipad/index.html
 a Filename - The pathname to the file on the machine.
http://www.apple.com:80/ipad/index.html

In JAVA, there is a URL class defined in the java.net package. We can create our own URL objects as follows:

URL webPage = new URL("http://www.apple.com/ipad/index.html");

JAVA will "dissect" the given String in order to obtain information about protocol, hostName, file etc...

Due to this, JAVA may throw a MalformedURLException ... so we will need to do this:

try {

URL webPage = new URL("http://www.apple.com/ipad/index.html");

} catch(MalformedURLException e) {

...

}
Another way to create a URL is to break it into its various components:

try {

URL webPage = new URL("http","www.apple.com",80,"/ipad/index.html");


} catch(MalformedURLException e) {

...

If you take a look at the JAVA API, you will notice some other constructors as well.

The URL class also supplies methods for extracting the parts (protocol, host, file, port and reference) of a URL
object. Here is an example that demonstrates what can be accessed. Note that this example only manipulates a
URL object, it does not go off to grab any web pages:

10
Here is the output:

http://www.apple.com:80/ipad/index.html
protocol = http
host = www.apple.com
filename = /ipad/index.html
port = 80 ref = null

After creating a URL object, you can actually connect to that webpage and read the contents of the URL by
using its openStream() method which returns an InputStream. You actually read from the webpage as if it were
a simple text file. If an attempt is made to read from a URL that does not exist, JAVA will throw an
UnknownHostException

EXAMPLE

Here is an example that reads a URL directly. It actually reads the file on wikipedia and displays it line by line to
the console. Notice that it reads the file as a text file, so we simply get the HTML code. Also, you must be
connected to the internet to run this code:

The output should look something like this, assuming you could connect to the webpage:

11
EXAMPLE

Here is a modification to the above example that reads the URL by making a URLConnection first. Since the
tasks of opening a connection to a webpage and reading the contents may both generate an IOException, we
cannot distinguish the kind of error that occurred. By trying to establish the connection first, if any IOExceptions
occur, we know they are due to a connection problem. Once the connection has been established, then any
further IOException errors would be due to the reading of the webpage data.

o Client/Server Communications

Many companies today sell services or products. In addition, there are a large number of companies turning
towards E-business solutions and various kinds of web-server/database technologies that allow them to conduct
business over the internet as well as over other networks. Such applications usually represent a client/server
scenario in which one or more servers serve multiple clients.

A server is any application that provides a service and allows clients to communicate with it.

Such services may provide:

 a recent stock quote

12
 transactions for bank accounts
 an ability to order products
 an ability to make reservations
 a way to allow multiple clients to interact (Auction)

A client is any application that requests a service from a server.

The client typically "uses" the service and then displays results to the user. Normally, communication between
the client and server must be reliable (no data can be dropped or missing):

 stock quotes must be accurate and timely


 banking transactions must be accurate and stable
 reservations/orders must be acknowledged

The TCP protocol, mentioned earlier, provides reliable point-to-point communication. Using TCP the
client and server must establish a connection in order to communicate. To do this, each program binds a socket
to its end of the connection. A socket is one endpoint of a two way communication link between 2 programs
running on the network. A socket is bound to a port number so that the TCP layer can identify the application to
which the data is to be sent. It is similar to the idea of plugging the two together with a cable.

The port
number is
used as the
server's
location on the machine that the server application is running. So if a computer is running many different server
applications on the same physical machine, the port number uniquely identifies the particular server that the
client wishes to communicate with:

The client and server may then each read and write to the socket bound to its end of the connection.

13
The server can communicate with only one client at a time.

The server waits for an incoming client request through the use of the accept() message:

When the accept() method is called, the server program actually waits (i.e., blocks) until a client becomes
available (i.e., an incoming client request arrives). Then it creates and returns a Socket object through which
communication takes place.
Once the client and server have completed their interaction, the socket is then closed:

Only then may the next client open a socket connection to the server. So, remember ... if one client has a
connection, everybody else has to wait until they are done:

So how does the client connect to the server ? Well, the client must know the address of the server as well as
the port number. The server's address is stored as an InetAddress object which represents any IP address (i.e.,
an internet address, an ftp site, local machine etc,...).

If the server and client are on the same machine, the static method getLocatHost() in the InetAddress class may
be used to get an address representing the local machine as follows:

14
Once again, a socket object is returned which can then be used for communication. Here is an example of what
a local host may look like:

The getLocalHost() method may, however, generate an UnknownHostException. You can also make an
InetAddress object by specifying the network IP address directly or the machine name directly as follows:

So how do we actually do communication between the client and the server ? Well, each socket has an
inputStream and an outputStream. So, once we have the sockets, we simply ask for these streams … and
then reading and writing may occu

Normally, however, we
actually wrap these input/output
streams with text-based,
datatypebased or object-
based wrappers:

You may look back at the notes on file I/O to see how to write to the streams. However, one more point ... when
data is sent through the output stream, the flush() method should be sent to the output stream so that the data is
not buffered, but actually sent right away.

Also, you must be careful when using ObjectInputStreams and ObjectOutputStreams. When you create an
ObjectInputStream, it blocks while it tries to read a header from the underlying SocketInputStream. When you
create the corresponding ObjectOutputStream at the far end, it writes the header that the ObjectInputStream is
waiting for, and both are able to continue. If you try to create both ObjectInputStreams first, each end of the
connection is waiting for the other to complete before proceeding which results in a deadlock situation (i.e., the
programs seems to hang/halt). This behavior is described in the API documentation for the ObjectInputStream
and ObjectOutputStream constructors.

Example:

Let us now take a look at a real example. In this example, a client will attempt to:

1. connect to a server

15
2. ask the server for the current time
3. ask the server for the number of requests that the server has handled so far
4. ask the server for an invalid request (i.e., for a pizza) Here is the server application. It runs forever, continually
waiting for incoming client requests:

16
Here is the client application:

17
o Datagram Sockets

Recall that with the datagram protocol (i.e., UDP) there is no direct socket connection between the client and the
server. That is, packets are received "in seemingly random order" from different clients. It is similar to the way
email works. If the client requests or server responses are too big, they are broken up into multiple packets and
sent one packet at a time. The server is not guaranteed to receive the packets all at once, nor in the same order,
nor is it guaranteed to receive all the packets.

Let us look at the same client-server application, but by now using DatagramSockets and DatagramPackets.
Once again, the server will be in a infinite loop accepting messages, although there will be no direct socket
connection to the client. We will be setting up a buffer (i.e., an array of bytes) which will be used to receive
incoming requests.

18
Each message is sent as a packet. Each packet contains:

 the data of the message (i.e., the message itself)


 the length of the message (i.e., the number of bytes)
 the address of the sender (as an InetAddress)
 the port of the sender

The server code for receiving an incoming packet involves allocating space (i.e., a byte array) for the
DatagramPacket and then receiving it. The code looks as follows:

We then need to extract the data from the packet. We can get the address and port of the sender as well as the
data itself from the packet as follows:

In this case the data sent was a String, although it may in general be any object. By using the sender's address
and port, whoever receives the packet can send back a reply.

EXAMPLE:

Here is a modified version of our client/server code ... now using the DatagramPackets:

19
20
ASSESSMENT

References
1. “Professional Java Programming” by Brett Spell, George Gongo, Wrox Publication, 2000, ISBN:
186100382X.

2. "The Complete Book of Middleware", 1st Edition by Judith M. Myerson, Auerbach Publications, 2002,
ISBN-13: 9780849312724

3. “Design patterns: elements of reusable object-oriented software” by Erich Gamma, Ralph Johnson,
Richard Helm, John Vlissides, Addison-Wesley, 1994, SBN:
4. 0201633612

5. “Architecture for Integration System” by Chris Chambers 2005 BBC R & D and EBU Project Group
P/MDP

Suggested Readings

1. https://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.199.3686&rep=rep1&type=pdf
2. http://www.dvs.tu-darmstadt.de/publications/pdf/IADIS-ICWI-2003.pdf

Reminder:

Submit this learning material securely packaged (please provide an extra plastic
envelope intended for the second set of learning materials) to the campus security personnel or
as advised by your subject teacher, on the prescribed date and time.

Prepared by:

MICHELLE P. OMBID
Instructor I

Approved by:

JARED HAREM Q. CELIS, MIT


College Dean

21

You might also like