CS 4321 Ch 3 Basing Software Development on Reusable Technology

convertingtownΛογισμικό & κατασκευή λογ/κού

4 Νοε 2013 (πριν από 3 χρόνια και 9 μήνες)

51 εμφανίσεις


1

CS
4321



Ch
3

Basing Software Development on Reusable Technology


Sections

Pages

3.1
-
3.
10

67
-
104


***
Much of these
notes
are

copied directly from the PP slides that accompany the text.


Section 3.1


Building on the Experience of Others


1.

Software

engineers should avoid re
-
developing software already developed
,
i.e.
shouldn’t reinvent the wheel.


2.

Types of reuse:




Reuse of expertise




Reuse of standard designs and algorithms




Reuse of libraries of classes or procedures



Reuse
of powerful commands
built into languages and operating systems




Reuse of frameworks




Reuse of complete applications



Section 3.2


Reusability and Reuse in S
E


1.

Reuse and design for reusability should be part of the culture of software development organizations. But, there
are problems to overcome:




Why take the extra time needed to develop something that will benefit
other

projects/customers?




Management may only reward the efforts of people who create the
visible ‘final products’
.



Reusable software is often created in a hu
rry and
without enough attention to quality
.


2.

A vicious cycle


Developers tend
to
not

develop high quality reusable components, so there is often little to reuse

To solve the problem, recognize that:





T
h
is

vicious cycle costs money




Investment

in reusable code is important




Attention

to
quality

of reusable components is essential

o

So that potential reusers have confidence in them

o

The quality of a software product is only as good as its lowest
-
quality reusable component




Developing

reusable components can often simplify design



Section 3.3
-

Frameworks


1.

A framework is reusable software that implements a generic solution to a generalized problem.




It provides common facilities applicable to different application programs.





2

2.

A

framework is intrinsically
incomplete





Certain

classes or methods are used by the framework, but are missing (
slots
)



Some functionality

is

optional,
a
llowance is made for developer to provide it
(
hooks
)



Developers use the
services

that the framework provides



Taken together
, the hooks, slots, and services

are called the Application Program Interface (
API
)


3.

In the object oriented paradigm, a framework is composed of a library of classes.




The API is defined by the set of all public
methods of these classes.



Some of the classes will normally be abstract



4.

Examples:

patient billing, payroll management, university registration, e
-
commerce, frequent buyer club,
etc
.
Why do framewrorks exist for these domains?


5.

Types of Framewor
ks


A
horizontal

framework provides general
application facilities that a large number of
applications can use

A
vertical

framework (
application framework)

is
more ‘complete’ but still needs some slots to be
filled to adapt it to specific application needs




6.

A
distributed system

is a system in which:




computations are performed by
separate programs




… normally running on separate pieces of hardware



… that
co
-
operate

to perform the task of the system
.





3

Section 3.
4



Client
-
Server Architecture


1.

Client
-
Server Architectu
re




A distributed system can be implemented with a Client
-
Server architecture.



A client
-
server system is composed of 1 or more servers and 1 or more clients


Server:



A program that
provides a service

for other programs

(clients)

that connect to it using a communication
channel
.



A server

may be accessed by many clients simultaneously
.

Client




A program that accesses a server (or several servers)
to

obtain services



2.

Sequence of activities in a client
-
server

syst
em



Client


Server

Time




Starts running



Listens for connections

Starts Running



Requests connection





Accepts connection, if willing

Send message requesting a service





Read message



Fulfills request for service



Send return message

Read
return message



Take action on message



etc
.






A server can stop listening for new connections (e.g. if it is “full”)



A server can disconnect a client.



A server can shut down.



A client can disconnect itself or shut down.


3.

Advantages of
client
-
server syste
ms




The work can be distributed among different machines



The clients can access the server’s functionality from a distance



The client and server can be designed separately



They can both be simpler



All the data can be kept centrally a
t the server



Conversely, data can be distributed among many different geographically
-
distributed clients or servers



The server can be accessed simultaneously by many clients



Competing clients can be written to communicate with the same server, and vice
-
v
ersa





4

4.

Example
s

of client
-
server systems

-


Many programs we use are client
-
server. The web is inherently client
-
server. The client is your web browser and the server is the web server that receives and processes page/service
requests. Any program that requests something across a network is almost
certainly client
-
server because there
has to be something on the other side to process the request,
e.g.
smart phone applications, email
, database
system,
etc
.


5.

Activities of a serv
er


1.

Initializes

itself


2.

S
tarts listening for clients


3.

Handles

the following

types of events

originating from clients


a.

accepts connections


b.

responds to messages


c.

handles
client

disconnection


4.

May stop
listening

5.

Must

cleanly terminate



Activity

Diagram



In
ternal events
, such as the completion of an activity

trigger
transition

State

Diagram



External

events trigger
state transitions







5

6.

Activities of a
client


1.

Initializes

itself


2.

Initiates a connection

3.

Sends messages to server

4.

Handles

the following types of
events

originating from
the
server

a.

responds to messages


b.

handles
server

disconnection


5.

May
disconnect itself

6.

Must

cleanly terminate











7.

Threads in a client
-
server system

(Sequence Diagram)






6

8.

Thin
-

versus fat
-
client systems


Thin
-
client

system



Client is made as small as possible



Most of the work is done in the
server.



Client easy to download over the
network


Fat
-
client

system



As much work as possible is
delegated to the clients.



Server can handle more clients




9.

Communications protocols




The messages the client sends to the server form a
language
.

The server has to be programmed to
understand that language.



The messages the
server

sends to the
client

also form a
language
.

The
client
has to be programmed to
understand that language.



When
a client and server are communicating, they are in effect having a conversation using these two
languages



The two languages and the rules of the conversation, taken together, are called the
protocol


10.

Tasks to perform to develop client
-
server applications


1.

Design the primary work to be performed by both client and server


2.

Design how the work will be distributed


3.

Design the
protocol, the
details of the set of messages that will be sent


4.

Design the mechanism for

a.

Initializing


b.

Handling connections


c.

Sending and

receiving messages


d.

Terminating






7

Section 3.5


Technlogy Needed to Build Client
-
Server Systems


1.

Overview




Transmission Control Protocol (TCP)

1.

Handles connections between two computers

2.

Computers can then exchange many IP messages over a connection

3.

Assures that the messages have been satisfactorily received



Internet Protocol (IP)

1.

Route messages from one computer to another


2.

Long messages are normally split up into small pieces




A server has a
host

which
has an
IP address

and a
host name

1.

Several servers can run on the same host.

2.

Each server is identified by a port number (0 to 65535).

3.

To initiate communication with a server, a client must know both the host name

(or IP address)

and the
port number




2.

Connecting


To connect a client and

server, we use classes from the
java.net

package: ServerSocket and Socket.

The
process goes like this:


a.

Turn server on (
e.g.

run a Java program)




b.

Tell server to create a socket where clients can request connections:

ServerSocket ss = new ServerSocket (

host, port )



8

c.

Tell server to start listening for connections:

Socket cs = ss.accept()


d.

A

client request
s

a connection:

Socket cs = new Socket ( host, port )


3.

Communication


a.

So far we have created a
TCP
pipe between the client and server using a Socket
on each side

as the
ServerSocket a
nd Socket classes implement TCP.




b.

Next, we add capabilities on the server and client to send and receive messages. One choice is to use the
ObjectOutputStream and ObjectInputStream, which implement IP. These are classes from the
java.io

package. Thus, together, these two ideas (sockets and

streams) implement TCP/IP in a Java program.




Now the Server (Client) can send messages:


out.writeObject ( obj )


And the Client (Server) can wait indefinitely to receive messages:


obj = in.readObject()



9

c.

To transmit objects in this fashion, they must

be Serializable. This is an important function of the java.io
package. To serialize an object means to convert an object into a stream of bytes that can later be
deserialized back into a copy of the original object.

To do this in Java we use the

Serializa
ble interface

which

does not have any


methods to override, it simply serves as a note to the JVM that the object will
need to be serialized at some point. So, making a serializable object is as simple as:


import java.io;

public class MyClass implements
Serializable

{


...


4.

Implementing Threads in Java


A thread is a part of a program that is setup to run on its own while the rest of the program does something
else. In other words, each thread is like a running program.

We use the
Thread

class in Java to define threads.

One way to implement a thread is to:


a.

Define a class that implements the
Runnable

Interface

b.

Override the
Run

method, this is the code the thread will execute

c.

In some other class, instantiate a
Thread
, t

d.

In this other cl
ass, invoke the
start

method for the thread: t.start(). This calls the
Run

method.

In a similar way, we can simply define a class that extends the Java
Thread

class. We will use the method
described previously.


Another method for implementing a thread is

to create a class that extends the Thread class. This class must
implement the Run() method. This technique is used on the server in the OCSF.


5.

Client Threads


a.

Both the Client and the Server will need multiple threads to operate. The Client will need two
threads:
one for receiving messages from the Server and one for getting input from a user. The way that we will
begin to think about implementing this is that the main method of some class will start a thread to listen
for messages from the server. Thus, t
he Run method for this thread might establish a connection and
then go into a loop that listens indefinitely.


public class ReadThread implements Runnable

{

...

final public void run()

{



Object msg;



clientSocket= new Socket(host, port);



output
= new ObjectOutputStream(clientSocket.getOutputStream());



input = new ObjectInputStream(clientSocket.getInputStream());



while(!readyToStop)



{



msg = input.readObject();



handleMessageFromServer(msg);



}

}





10

b.

When a message is r
eceived it is passed to a method, handleMessageFromServer for any processing. The
main method might
have
code like this:


ReadThread rThreadObj = new ReadThread();

Thread rThread = new Thread(rThreadObj);

rThread.start();


c.

The main method will act as a thr
ead itself with the inclusion of code like this:


BufferedReader fromConsole =



new BufferedReader(new InputStreamReader(System.in));

String message;

while (true)

{



msg = fromConsole.readLine();



handleMessageFromUser(msg);

}


This is the basic
idea. You will see that when the authors develop the OCSF, they will do things a bit
differently.


6.

Server Threads


The Server will need
the following threads:


1.

One that

listens for connections.

2.

One t
hat interacts with the user responsible for administering the server.

3.

One
for each connection to a client so that independent communication can take place with each
client. The Server implements these threads as a ThreadGroup.


In general, n+2 threads ar
e needed, where n is the number of active connections.

Thus,
the server maintains
a thread for communicating with each client.






11

7.

Thread Example

(optional)


This simple example illustrates a "main" thread and a "second" thread. The "main" thread will (a)
start the
second thread, (b) accept input from the user and echo it to the console. The "second" thread will print a
message approximately every second.


import java.io.*;

public class MainThread

{

public static void main(String[] args)

{



SecondThread
sThreadObj = new SecondThread();



Thread sThread = new Thread(sThreadObj);



sThread.start();



int i = 1;



try



{



BufferedReader fromConsole =



new BufferedReader(new InputStreamReader(System.in));



String message;




while (true)



{



message = fromConsole.readLine();



System.out.println(i++ + "
-
" + message



+ ", in Main Thread");



}



}



catch (Exception ex) {}

}

}

public class SecondThread implements Runna
ble

{

public void run()

{



int i = 1;



while(true)



{



try



{



Thread.sleep(1000);



System.out.println(i++ + "
-
in sThread loop");



}



catch(InterruptedException e) {}



}

}

}






12

Section 3.6


Th
e Object Client
-
Server Framework (OCSF)


1.

The OCSF is
a simple Java

framework
, developed by the authors of your text,

that allows you to pass Objects
back and forth
between a client and a server. It is a very broad (or general
, horizontal
) framework, in fac
t,
maybe the most general. The only services available, besides connection related services are the ability to
send and receive Objects. The user of this framework must supply
an implementation for two critical
methods (slots). The methods tell the server
(client) what to do with an Object it receives from the client
(server). These two methods are:


handleMessageFromServer( obj )





AbstractClient class

handleMessageFromClient( obj, client )





AbstractServer class


1.

The OCSF is a set of
three
classes
.
You never modify these classes, you:


a.

Create subclasses

of the
AbstractClient and AbstractServer classes


b.

Call public methods

that are provided by the framework

c.

Override

certain slot and hook methods (explicitly designed to be overridden)



A simplified
version of the class diagram for the OCSF

is:







13

The comple public/protected interface
for the OCSF

is:




2.

To building an application using the OCSF:


a.

Define a communications protocol. This defines

the allowable messages/objects that can be sent and
received.


b.

Create a s
ubclass
of Abstract
Client and implement:
handleMessageFromServer( obj )


c.

Create a s
ubclass
of Abstract
Server and implement:
handleMessageFromClient( obj, client )














14

Section 3.7


The Client Side


1.

The AbstractClient Class
provides the following:


Hooks

-

These methods may be overridden in a concrete subclass.


1.

connectionEstablished

2.

connectionClosed

3.

connectionException


Slots

-

The implementation for this method must be supplied by a concrete subclass.


1.


handleMessageFromServer( obj )


Services

-

These services are inherited by concrete subclasses. They cannot be overridden.


1.

openConnection, closeConnection, isConnected

2.

sendToServer

3.

getPort, setPort, getHost, setHost, getInetAddress


Section 3.8


The Server Side


1.

The AbstractServer Class
provides the following:


Hooks

-

These methods may be overridden in a concrete subclass.


1.

serverStarted, serverStopped, serverClosed

2.

clientConnected, clientDisconnected, clientException

3.

listeningException


Slots

-

The implementation for this method must be supplied by a concrete subclass.


1.


handleMessageFromClient( obj, client )


Services

-

These services are inherited by concrete subclasses. They cannot be overridden.


1.

listen, stopLisening, isListening

2.

close

3.

sendToAllClients

4.

getClientConnections, getNumberOfClients

5.

getPort, setPort

6.

setTimeout, setBacklog


2.

The ConnectionToClient Clas
s
is a concrete class which
provides the following:


Services

-

These services are available to any subclass of
AbstractServer
.


1.

sendToClient

2.

close

3.

getInfo, setInfo

4.

getInetAddress


15


3.

Internals
:


a.

The
setInfo

and
getInfo

methods make use of a Java class called
HashMap
.
This is a very useful feature of
the framework. You can store anything associated with a client there. You might store a login id and
password, and any data that was useful. The HashMap specifies a String
key and an Object value.


b.

Many methods in the server side are
synchronized

c.

The collection of instances of

ConnectionToClient
is stored using a special class called

ThreadGroup

d.

The server must pause from listening every 500ms to see if the

stopListening
me
thod has been called

if not,
then it resumes listening immediately


Section 3.9


Simple Chat: An Instant Messaging Application


As an example, the SimpleChat program has been develop
ed

using the OCSF.
The program is very simple. Any
client can send a text message to the server which turns around and sends the message to all the clilents that are
connected. Thus, the client is named
ChatClient
and the server is named
EchoServer.


SimpleChat

passes strin
gs back and forth between client and server. Since String is an Object and implements
Serializable, this is no problem. However, remember that i
f we want to pass Objects back and forth between
client and server, we have to make sure that the objects implem
ent the Serializable interface.


1.

SimpleChat


The class diagram for the SimpleChat application is
shown below. Once the server is started, clients can
connect and send messages to the server. All
messages received by the server are simply echoed
to all the

connected clients.


Note the separation of the UI (
ClientConsole
) and the
client (
ChatClient
).
This allows us to separate UI code
from code that is communicating with the server.
The application is also made more general by
implementing the
ChatIF

interfa
ce. This interface
simply says that any UI must implement a
display

method. The
ClientConsole

is the main class and it
maintains a link to the
ChatClient
.
ChatClient

maintains a link to the
ClientConsol
through the

ChatIF
. Thus, when
handleMessageFromServer

is
called (automatically), it can then (in general) do
some processing, and then display the results by
calling: this.clientUI.display(msg). In other words, it
doesn't care how
display

is implemented. Thus, we
can substitute a class
, say
ClientGUI

for
ClientConsole,
that would implement the display
method for a GUI.







16

2.

Using SimpleChat


Open three command windows and set the folder

for each
to the location of the simplechat
application.


a.

In one window start the server: java
EchoServer

b.

In another window start a client: java ClientConsole

c.

In another window start a second client: java ClientConsole

d.

Type a message in a client window and press Enter. You should see the message echoed to the server and all
other clients.

e.

Kill the s
erver and clients with Ctrl+c.


3.

Understanding SimpleChat


View ClientConsole, ChatClient, and EchoServer to learn more about how this is
working.


Note:

a.

You could build a ServerConsole and modify EchoServer so that the server operates like ClientConsole
and ChatClient.

b.

You could add features, using the framework services so that disconnection and termination are
handled gracefully.


4.

Internals


Running the Server

(Optional)


This is somewhat of a sequence diagram that shows what happens when the client r
uns.


main()

es = new EchoServer(...)


// sets things up

es.listen()


// listens for requests for connections


listen()

establish socket if necessary

define and start listening thread


run()

Loop:

cs = ss.accept()


// waits for request

c = new
ConnectionToClient()


ConnectionToClient()

establish socket and IO

starts a thread for client


run()

Loop:

msg = input.ReadObject()

server.receiveMessageFromClient()


receiveMessageFromClient()

handleMessageFromClient


handleMessageFromClient()

sendToAllClients(msg)



17

5.

Internals


Running the Client.
This is somewhat of a sequence diagram that shows what happens when the
client

runs.

(Optional)


main()

ui = new ClientConsole()


// Instantiate the UI/GUI


ClientConsole()

c = new ChatClient()


// Ins
tantiate the client


ChatClient()

this.openConnection()


openConnection()

establish socket and IO

define and start a thread for client


run()

Loop:

msg = input.ReadObject()

handleMessageFromServer(msg)


handleMessageFromServer()

ui.display(msg)


ui.accept()


// Wait for input from the console


accept()

msg = fromConsole.readLine();

c.handleMessageFromClientUI(msg)


handleMessageFromClientUI()

sendToServer(msg)


sendToServer()

output.writeObject(msg)







18

Chapter 3 Homework


1.

Explain what a
framework is in as much detail as possible.

2.

Discuss several reasons why developers are reluctant to develop reusable libraries.

3.

Briefly discuss what a distributed system is.

4.

Briefly discuss at least four advantages that the client
-
server architecture
provides

5.

Describe the concurrency in the client software and the server software.

6.

Discuss the major ways that work can be distributed in a client
-
server system.

7.

What is a communication protocol? How is it used in a client
-
server system?

8.

Design a protocol f
or a simple system.

9.

Draw/understand a class diagram of the OCSF. Same for the SimpleChat application.

10.

Describe several hooks, several services, and the slot that are provided on the client side of the OCSF. Same for
the server.

11.

Write
(pseudo)
code to build a
simple
system
that uses
the OCSF.

12.

Discuss several risks associated with developing reusable components.

13.

Discuss several risks associated with using reusable components.

14.

(omit) Write code to implement a simple thread.

15.

Design a protocol for a

banking system that will be developed using the OCSF. The system allows for multiple
users who can do the usual things such as login, check balance, withdraw, add funds, write checks, etc.

Only
(custom) objects should be passed using the OCSF (i.e. no str
ings) You should include a class diagram of all
classes you design. You should also have a report detailing your protocol design providing ample detail.

Be sure
and address what happens when a message is received,
i.e.
what processing takes place and possi
bly any
communication back to the originator. Be carful with multipart data or a multipart diaglog. For instance, a client
sends a request, the server asks for more detail, the client responds. How does the server know what part of a
transaction a client i
s on when it is simultaneously receiving requests from other clients. Hint: use
setInfo.