1 / 35

Streams

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

affrica
Télécharger la présentation

Streams

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. data1 data2 data3 data4 data5 data6 data7 PART 1 Streams data8 data7 data6 data5 data4 data3 data2 data1 Stream1 Stream2 data8

  2. 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.

  3. Component Operation( ) Decorator ConcreteComponent component->Operation() Operation( ) Operation( ) ConcreteDecoratorB ConcreteDecoratorA Operation( ) Decorator::Operation() Operation( ) AddedBehavior() AddedBehavior() Decorator Patern component

  4. 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

  5. InputStream FileInputStream DataInputStream Example: DataInputStream Abstract class Concrete class Decorator

  6. 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

  7. Output Streams (Java 1.0) OutputStream ByteArray File Filter Piped OutputStream OutputStream OutputStream OutputStream Data Buffered PrintStream OutputStream OutputStream

  8. 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.

  9. 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

  10. 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

  11. “Highest” Level Input Stream FileInputStream InputStreamReader BufferedReader FileInputStream ObjectInputStream ZipInputStream Other Important Input Streams:

  12. “Highest” Level Output Stream Other Important Output Streams: PrintWriter PrintStream FileOutputStream ObjectOutputStream ZipOutputStream

  13. 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

  14. Part 2 Sockets and Serializtion of Objects

  15. TCP/IP Application Model Application TCP UDP IP Network Protocols Protocol Stack

  16. 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.

  17. 0 16 31 UDP Header Format Destination Port Source Port Checksum Length Data

  18. Application process Application process Application process UDP Ports Queues Packets demultiplexed Packets arrive

  19. 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();}

  20. 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

  21. 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

  22. 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.

  23. 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.

  24. 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

  25. 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){ }

  26. ServerSocket • Wait and listen to a port for a socket trying to connect • Return the connecting socket • Close the ServerSocket

  27. 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); }

  28. 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

  29. ObjectOutputStream out File FileOutputStream ObjectInputStream in FileInputStream (Shape) s = in.ReadObject() Serialization of Objects Serialized Shape s out.WriteObject(s) Retrieved Object

  30. 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

  31. 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.

  32. 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

  33. Server Examples • Day Time Server • Echo Server • File Version of Echo Server

More Related