350 likes | 487 Views
data1. data2. data3. data4. data5. data6. data7. PART 1. Streams. data8. data7. data6. data5. data4. data3. data2. data1. Stream1. Stream2. data8. Input Streams (Java 1.0). InputStream. ByteArray File Filter Piped Sequence StringBuffer
E N D
data1 data2 data3 data4 data5 data6 data7 PART 1 Streams data8 data7 data6 data5 data4 data3 data2 data1 Stream1 Stream2 data8
Input Streams (Java 1.0) InputStream ByteArrayFileFilter PipedSequenceStringBuffer InputStreamInputStreamInputStreamInputStreamInputStreamInputStream 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.
Component Operation( ) Decorator ConcreteComponent component->Operation() Operation( ) Operation( ) ConcreteDecoratorB ConcreteDecoratorA Operation( ) Decorator::Operation() Operation( ) AddedBehavior() AddedBehavior() Decorator Patern component
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
InputStream FileInputStream DataInputStream Example: DataInputStream Abstract class Concrete class 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) • 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 bytehierarchy in combination with those in the characterhierarchy. 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 Reader converter: InputStreamReader InputStream Writer converter: OutputStreamWriter OutputStream FileInputStream FileReader StringReader StringBufferInputStream No corresponding class StringWriter ByteArrayInput/OutputStream CharArrayReader/Writer 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 (same) DataInputStream PrintStream PrintWriter LineNumberInputStream LineNumberReader PushBackInputStream PushBackReader
“Highest” Level Input Stream FileInputStream InputStreamReader BufferedReader FileInputStream ObjectInputStream ZipInputStream Other Important Input Streams:
“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
TCP/IP Application Model 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.
0 16 31 UDP Header Format Destination Port Source Port Checksum Length Data
Application process Application process Application process UDP Ports Queues Packets demultiplexed Packets arrive
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 For reliable, in order delivery For flow control For process demultiplexing Other fields Destination Port Source Port Sequence Number (byte count) Acknowledgement 0 Flags Advertised Window HdrLen Checksum Urgent Pointer Options (variable length) Data
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.
Two Types of Sockets 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.
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
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 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){ }
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 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 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); }
Client 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
ObjectOutputStream out File FileOutputStream ObjectInputStream in FileInputStream (Shape) s = in.ReadObject() Serialization of Objects Serialized Shape s out.WriteObject(s) Retrieved Object
Serialization of Objects class DragRect extends Rectangle implements Serializable{…} abstractclass Shape implements Serializable{ protected DragRect boundsBox; protected Color color; abstractvoid 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
Server Examples • Day Time Server • Echo Server • File Version of Echo Server