Title: Streams
1PART 1
Streams
data1
data8
data7
data6
data5
data4
data3
data2
Stream1
Stream2
data8
2Input 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.
3Decorator 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
4Decorator Patern
component
5Example DataInputStream
Abstract class
Concrete class
Decorator
The Decorator class is a concrete derived class
from the abstract class FilterInputStream.
6Example 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
7Output Streams (Java 1.0)
OutputStream
ByteArray File
Filter
Piped OutputStream OutputStream
OutputStream OutputStream
Data Buffered
PrintStream OutputStream
OutputStream
8Reader and Writer Classes (Java 2)
- Java 1.1 added new classes into the InputStream
and OutputStream hierarchy. It did not replace
those classes. - The new Reader/Writer classes provide Unicode
compliant character based I/O. - 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.
9byte streams
char streams
10byte streams
char streams
11Correspondence between the two hierarchies
Sources and Sinks Java 1.0 Classes
Corresponding Java 1.1 Classes
Reader converter InputStreamReader
InputStream
Writer converter OutputStreamWriter
OutputStream
FileInputStream
FileReader
StringReader
StringBufferInputStream
StringWriter
No corresponding class
ByteArrayInput/OutputStream
CharArrayReader/Writer
PipedInput/OutputStream
PipedReader PipedWriter
12Modifying 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
(same)
DataInputStream
PrintStream
PrintWriter
LineNumberInputStream
LineNumberReader
PushBackInputStream
PushBackReader
13Highest Level Input Stream
FileInputStream InputStreamReader BufferedReader F
ileInputStream ObjectInputStream ZipInputStream
Other Important Input Streams
14Highest Level Output Stream
Other Important Output Streams
PrintWriter PrintStream FileOutputStream ObjectOut
putStream ZipOutputStream
15Example 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
16Part 2 Sockets and Serializtion of Objects
17TCP/IP Application Model
Application
TCP
UDP
IP
Network Protocols
Protocol Stack
18UDP 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.
19UDP Header Format
Destination Port
Source Port
Checksum
Length
Data
20Ports
Queues
Packets demultiplexed
Packets arrive
21Creating 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) DatagramPacke
t 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 byte256 datagramPacket pkt
new DatagramPacket(sbuff, sbuff.length) trysds
.receive(pkt) catch(IOException ie)
ie.printStackTrace()
22TCP 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/demultiplex
ing of packets
23TCP Packet Format
For reliable, in order delivery
For process demultiplexing
For flow control
Other fields
Destination Port
Source Port
Sequence Number (byte count)
Acknowledgement
Advertised Window
Flags
0
HdrLen
Checksum
Urgent Pointer
Options (variable length)
Data
24Port 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.
25Sockets
Two Types of Sockets
-- Provides the streams for communication!
Server Sockets
-- Provides the ability to wait and listen
to a port for someone to try to connect via
a socket.
26Socket
- 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
27Example TCP Client Socket -- code fragment
try theSocket new
Socket(hostname,7) theInputStream new
BufferedReader(new InputStreamReader(theSocket.g
etInputStream())) 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)
28ServerSocket
- Wait and listen to a port for a socket trying to
connect - Return the connecting socket
- Close the ServerSocket
29Example TCP Server Socket code fragment
try theServer new ServerSocket(echoPo
rt) 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)
30(No Transcript)
31(No Transcript)
32Client Examples
- 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
33Server Examples
- Day Time Server
- Echo Server
- File Version of Echo Server
34Persistence of Objects
Saving your work
Object persistence means that an objects
lifetime is not limited to the time that a
program is executing. Object serialization
permits an object to be saved to a disk and
restored when the program is re-invoked.
35Object Serialization
In order to be able to save and restore an object
- The Class of that object must implement the
Serializable Interface
This Interface is just a flag and has no
methods.
Many classes in the standard library are
serializable. These include the wrapper classes,
all of the Collection classes, and many others.
- Create a FileOutputStream
- Wrap the FileOutputStream inside an
ObjectOutputStream
- Call method writeObject( ) of ObjectOutputStream
To restore the object
- Wrap an ObjectInputStream around a FileInputStream
- Call method readObject( ) and downcast the object
36Serialization of Objects
Serialized Shape s
out.writeObject(s)
Retrieved Object
37Serialization 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 //inherits
Serializable through HollowRectangle from
Shape //derived classes inherit Serializable
from the base class
38Serialization of Objects
Shape
boundsBox
color
x2y4width12length20
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.
39Serialization of Objects
To save and restore an ArrayList of Shape objects
- Be sure that class Shape and its components such
as DragRect are serializable.
- Wrap an ObjectOutputStream around a
FileOutputStream
ObjectOutputStream out new ObjectOutputStream(n
ew BufferedOutputStream(new
FileOutputStream (filename.dat)))
- Use method writeObject( ) to store the ArrayList
object, theShapes, in a file.
out.writeObject(theShapes)
40Serialization of Objects
To restore the ArrayList (and its contents)
- Wrap an ObjectInputStream around a
FileInputStream object
ObjectInputStream in new ObjectInputStream(new
BufferedInputStream( new
FileInputStream(filename.dat)))
- Use method readObject in the ObjectInputStream to
restore the ArrayList. You must down cast the
Object retrieved from memory to its original
class type.
try theShapes (ArrayList)(in.readObject(
)) catch (IOException e)
When restoring objects from a (binary) file, you
must read them into your program in the same
order in which you wrote them to the file.
41Serialization 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
42Piped Input/Output Files
PipedInputStream and PipedOutputStream are used
to transfer data from one process (active thread)
to another.
A PipedInputStream is created, then a
PipedOutputStream is created and attached to the
PipedInputStream. Both Streams may be wrapped in
a DataInput/OutputStream for passing individual
data types.
PipedInputStream pin new PipedInputStream( )
PipedOutputStream pout new PipedOutputStream(pi
n)
One process writes to pout (inserts data into the
pipe. The other process reads this data from
pin (other end of the pipe)
43Communication Between Two Threads
outStream.writeInt(21)
inStream.readInt( )
Process B
Process A
PipedInputStream pin new PipedInputStream( )
PipedOutputStream pout new PipedOutputStream(pi
n)
DataInputStream inStream new
DataInputStream(pin) DataOutputStream outStream
new DataOutputStream(pout)