Lecture 10 -- Streams and Sockets

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

2 Δεκ 2013 (πριν από 3 χρόνια και 8 μήνες)

107 εμφανίσεις

Streams

data1

data8

data7

data6

data5

data4

data3

data2

Stream1

Stream2

data2

data1

data3

data4

data5

data6

data7

data8

PART 1

Input Streams (Java 1.0)

InputStream

ByteArray

File

Filter

Piped

Sequence

StringBuffer

InputStream

InputStream

InputStream

InputStream

InputStream

InputStream


Data Buffered LineNumber Pushback

InputStream InputStream InputStream InputStream

There are two categories of input streams.
Those classes that are tied to a physical
input source and read values from a file, byte array, pipe, or string buffer.

The second category consists of those input streams that are virtual and depend
upon another input stream for the actual reading operations but extend the
functionality of that stream in some manner.

Decorator Patern

Component

Operation( )

ConcreteComponent

Operation( )

ConcreteDecoratorA

Operation( )

component
-
>Operation()

Decorator

Operation( )

component

Decorator::Operation()

AddedBehavior()

ConcreteDecoratorB

Operation( )

AddedBehavior()

Decorator Pattern

The Decorator pattern provides a flexible way of adding features to
individual objects, not an entire class. The Decorator pattern is also known
as a Wrapper.

A Decorator


Encloses a component in another object that adds features


Conforms to the interface of the component it decorates.


Forwards requests to the component it encloses


Performs additional actions


May be nested recursively

Example: DataInputStream

InputStream

FileInputStream

Abstract
class

Concrete class

DataInputStream

Decorator

Example of Nesting Decorator Classes

//Create a FileInputStream, wrap a Buffered InputStream around it,

//and then wrap a DataInputStream around that.

DataInputStream theDIS;

theDIS =
new

DataInputStream(
new

BufferedInputStream(
new


FileInputStream(“theFilePathAndName”)));

Method Invocations

int

myVal = theDIS.readInt();

//method in DataInpustStream

theDIS.mark();



//method in FilterInputStream class

theDIS.close();




//inherited from InputStream


Output Streams (Java 1.0)

OutputStream

ByteArray File Filter Piped

OutputStream OutputStream OutputStream OutputStream

Data Buffered PrintStream

OutputStream OutputStream

Reader and Writer Classes (Java 2)

1.
Java 1.1 added new classes into the InputStream and
OutputStream hierarchy. It did not replace those classes.

2.
The new Reader/Writer classes provide Unicode compliant
character based I/O.

3.
There are times when you must use classes from the Java 1.0
byte

hierarchy

in combination with those in the
character

hierarchy
. Bridge classes are provided for this task:


InputStreamReader

converts an
InputStream

to a
Reader
.


OutputStreamWriter

converts an
OutputStream

to a
Writer
.

Correspondence between the two hierarchies

Sources and Sinks


Java 1.0
Classes

Corresponding Java 1.1 Classes

ByteArrayInput/OutputStream

StringWriter

InputStream

Reader
converter
:
InputStreamReader

OutputStream

Writer
converter
:
OutputStreamWriter

FileInputStream

FileReader

StringBufferInputStream

StringReader

CharArrayReader/Writer

No corresponding class

PipedInput/OutputStream

PipedReader PipedWriter

Modifying Stream Behavior

Filters: Java 1.0 class

Corresponding Java 1.1 class

FilterInputStream (
abstract
)

FilterReader (
abstract
)

FilterOutputStream (
abstract
)

FilterWriter
(abstract with no
subclasses
)

BufferedInputStream

BufferedReader

BufferedOutputStream

BufferedWriter

DataInputStream

(same)

PrintStream

PrintWriter

LineNumberInputStream

LineNumberReader

PushBackInputStream

PushBackReader

InputStream Class
Constructor
No constructor. This is an abstract class.
Instance methods
int
read(
byte
[] b)
int
read(
byte
[] b,
int
off,
int

len)
Reads bytes into array b. Returns the number
of bytes read.
void
close()
Closes the
InputStream.
“Highest” Level Input Stream

Other Important Input
Streams:

FileInputStream

InputStreamReader

BufferedReader

FileInputStream

ObjectInputStream

ZipInputStream

OutputStream Class
Constructor
No constructor. This is an abstract class.
Instance methods
public abstract void
write(
int
b)
public abstract void
write(
byte[]
b)
Writes a byte of data.
Writes all bytes of data in the array b.
public void
flush()
Flushes the output stream.
void
close()
Flushes and closes the
OutputStream.
“Highest” Level Output Stream

Other Important Output
Streams:

PrintWriter

PrintStream

FileOutputStream

ObjectOutputStream

ZipOutputStream

Example of use of Input/Output Streams

Discussion
of typical uses of I/O streams

Program Source code

Output files

Original file with line numbers

"That's pi" file

The two files concatenated

Part 2 Sockets and Serializtion of Objects

TCP/IP Application
Model

Client
Server
Internet
TCP/IP
(socket)
TCP/IP
(socket)
Application

TCP

UDP

IP

Network Protocols

Protocol Stack

UDP Connectionless Transport Protocol

UDP extends the host
-
host delivery service of the underlying
network into a process
-
process communication service.


Provides a multiplexing/demultiplexing service to allow
multiple processes on each host to share the network.


Ensures correctness of the message by use of a checksum.


Adds no other functionality beyond “best effort” delivery
service of the underlying network.

UDP Header Format

Source Port

Destination Port

Checksum

Length

Data

0

16

31

Application


process

Application


process

Application


process

Packets
arrive


UDP

Ports

Queues

Packets
demultiplexed

Creating UDP Datagrams

Client Code fragment

DatagramSocket ds = new DatagramSocket ();

int portNumber = ds.getLocalPort();

byte buff[ ] = {‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘ ‘, ‘w’, ‘o’, ‘r’, ‘l’, ‘d’};

InetAddress address = InetAddress.getByteName(“academic”);

DatagramPacket packet = new DatagramPacket(


buff, buff.length, address, portNumber);

try{ ds.send(packet);}

catch (IOException ie) {ie.printStackTrace();}

Server
sds

Code fragment for receiving the datagram

byte sbuff[ ] = new byte[256];

datagramPacket pkt = new DatagramPacket(sbuff, sbuff.length);

try{sds.receive(pkt);}

catch(IOException ie) {ie.printStackTrace();}

TCP a Reliable Byte Stream Protocol

TCP (Transport Control Protocol) is a connection oriented protocol
that guarantees the reliable, in
-
order delivery of a stream of bytes.


TCP is full
-
duplex (it supports a pair of byte streams flowing
in opposite directions.)


It provides for flow control which allows a receiver to limit the
rate at which a sender can transmit.


It implements a congestion control mechanism which throttles
the sender from overloading the network.


Like UDP, it provides for multiplexing/demultiplexing of
packets

TCP Packet Format

Source Port

Destination Port

Sequence Number (byte count)

Acknowledgement

Checksum

Urgent Pointer

Data

Options (variable length)

Advertised Window

HdrLen

Flags

0

For process demultiplexing

For reliable, in order
delivery

For flow control

Other fields

Port: An abstraction for locating services

Each service is associated with a given port number on a given
machine. When you ask for a particular port, you are
requesting the service associated with that port number.

There are 2 ** 16 available numbers, but the numbers 1


1024
are reserved for “well
-
known” services and should not be used
for user initiated services.

Port number 7 is used for the echo server and

Port number 13 is used for the time and date service

It is up to the client to know which port number the desired
service is running on.

Sockets

Server Sockets

Two Types of Sockets

--

Provides the streams for communication!

--

Provides the ability to wait and


listen to a port for someone to


try to connect via a socket.

Socket


Try to connect to a server listening to a particular port.



Return an InputStream



Return an OutputStream



Read from the InputStream



Write to the OutputStream



Close the connection

Example: TCP Client Socket
--

code fragment


try


{ theSocket =
new

Socket(hostname,7);


theInputStream =
new

BufferedReader(
new



InputStreamReader(theSocket.getInputStream()));


theOutputStream =
new

PrintStream(theSocket.getOutputStream());


userInput =
new

BufferedReader(new InputStreamReader(System.in));


while
(true){


theLine = userInput.readLine();


if
(theLine.equals("."))



{theOutputStream.println(theLine);



theSocket.close();
break
;}


theOutputStream.println(theLine);


System.out.println(theInputStream.readLine());


}

}

catch
(UnknownHostException e)


System.err.println(e);}

catch
(IOException e){ }

Connect to a server

(dest. addr., port number)

Return input stream

Return output

stream

Get client input from console

Write to OutputStream

Read from InputStream

Close the connection

ServerSocket


Wait and listen to a port for a socket trying
to connect



Return the connecting socket



Close the ServerSocket

Example: TCP Server Socket


code fragment

try

{ theServer =
new

ServerSocket(echoPort);


try
{


while
(true) {


Socket theConnection = theServer.accept();


System.out.println("Connection established with " + theConnection);


Responder theResponder =
new

Responder(theConnection);


Thread t1 =
new

Thread(theResponder);


t1.start();


}


}


catch

(IOException e)


{ theServer.close();


System.err.println(e);


}

}

catch
(IOException e)


{ System.err.println(e); }

Listen to a port for a socket

trying to connect

Return the connecting socket

Create a new thread to
handle the connection and
continue to listen for
additional requests

Close the Server Socket if exception
is raised

Socket Class
Constructor
Socket
(
String
host,
int
port)

throws

IOException,

UnknownHostException
Creates a socket and tries to connect to a
port
on a
remote
host
.
Instance methods
InputStream
getInputStream()
OutputStream
getOutputStream()
Returns the
InputStream and
OutputStream
associated with the Socket.
void
setSoTimeout(
int
millis)
Sets the blocking time on the Socket for reads.
void
close()
throws

IOException
Closes the Socket.
ServerSocket Class
Constructor
SererSocket
(
int
port)
throws

IOException
Creates a
ServerSocket that monitors a
port.
Instance methods
Socket
accept()
)
throws

IOException
Blocks waiting for a connection. Returns a Socket
through which communication with the client is
made.
void
close()
throws
IOException
Closes the
ServerSocket

Look for a particular port on a host.



Look for all ports on a host



Get the time from a DayTime Server



Echo Client



Applet EchoClient



Client Examples

Serialization of Objects

Serialized Shape s

File

FileOutputStream

ObjectOutputStream out

FileInputStream

ObjectInputStream in

Retrieved Object

out.WriteObject(s)

(Shape)

in.ReadObject()

s =

Serialization of Objects


class

DragRect
extends

Rectangle
implements

Serializable{…}


abstract

class

Shape
implements

Serializable{



protected

DragRect boundsBox;


protected

Color color;



abstract

void

draw(Graphics g);

}

class

FilledRectangle
extends

HollowRectangle {…..}


inherits Serializable through HollowRectangle from Shape

Serialization of Objects

Shape

boundsBox

color

x=2:y=4:width=12;length=20

Serialization saves an image of the object, and follows
all of the references contained in the object, saves all of
those objects, and continues the process of following
references and saving objects.

Serialization Demo

A linked list of six objects, each of which consists of one of the first 6
letters of the alphabets and a randomly generated 3 digit number
inside of parentheses, is generated, written into an output file, and
then retrieved from this file and, together with the contents of the
linked list in memory, written back to the screen for comparison.

Code for the Serialization Demo

Output file for Serialization Demo


Day Time Server



Echo Server



File Version of Echo Server



Server Examples