1 / 59

Starting Child Process, Special Components, I/O Streams, Client-Server, Multithreading, Multicasting

This lecture covers topics such as starting a child process, using special graphical components like JEditorPane and JTable, working with I/O streams, and implementing client-server communication with sockets, including multithreading and multicasting.

smithoscar
Download Presentation

Starting Child Process, Special Components, I/O Streams, Client-Server, Multithreading, Multicasting

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. CS441 CURRENT TOPICS IN PROGRAMMING LANGUAGES Lecture 6 George Koutsogiannakis /Summer 2011

  2. Topics • Starting a child process. • More on Special Graphical Components. • JEditorPane / JTable Editable and Selectable cells. • I/O Streams • Client Server / Using sockets. • Client / Server steps for Connection Oriented • Multithreaded server • Connectionless Client / Server • Multicasting

  3. Start Child Process public class StartChildProcess { public static void main(String[] args) { Runtime rt=Runtime.getRuntime(); Process proc; String cmd[]=new String[3]; cmd[0]="V1T4.exe"; cmd[1]="newtst22.txt"; cmd[2]="6"; try { proc=rt.exec(cmd); DataInputStream in=new DataInputStream(proc.getInputStream()); byte[] buf=new byte[256]; int cbRead=0; while(cbRead>=0) cbRead=in.read(buf); in.close(); String str=new String(buf); //write the data into a file FileOutputStream file=new FileOutputStream("testout.txt"); OutputStreamWriter out=new OutputStreamWriter(new BufferedOutputStream(file)); out.write(str); out.flush(); file.close();} catch(IOException e) {System.out.println(e);}} } C java C exe Data stream

  4. Start Child Process • The child process is a C program that has a main that takes as arguments two parameters. main(argc, argv) • Where argc is an integer that represents the number of arguments • And argv is an array of Strings that represents the arguments to be passed to this process. The first entry into the array is always the name of the child process’ executable. • For more details see example posted on the course ‘ s web site: start a child process with a Java program.

  5. JEditorPane Component • Special component that can display different formats of files. • It supports: • HTML. • RTF (Rich Text Format). • Special purpose applications via a ‘Editor Kits”. • Display could be editable by the user and saved.

  6. JEditorPane Component • Usage: • Within try/catch block that captures IOException: Create an object of the class: JEditorPane editorpane= new JEditorPane (url ); Where url is a String that points to either a web resource (i.e. http://localhost:8080/MyWeb/index.html) Or to a file in the local system (i.e. file://C:/MyPrograms/index.html) • editorpane.set(false); prevents editing on the text area.

  7. JEditorPane Component • Register the component with a listener so that when user clicks on a url the file gets retrieved and displayed: html.addHyperlinkListener(this); • Add the editor pane component to a container like a JPanel (possibly add it to a JScrollPane before adding it to a JPanel). • Override the hyperlinkUpdate method of the HyperlinkListener Interface.

  8. JEditorPane Component • public void hyperlinkUpdate ( HyperlinkEvent e) { if (e.getEventType() = = HyperlinkEvent.EventType.ACTIVATED) try { editorpane.setPage(e.getURL()); ………………………………………………………… ………………………………………………………………………. • It is assumed that a text field has been created with the proper listener for the text field where the user can type the url that leads to the file to be displayed. • For more details see example poste don the course ‘s web site:browser.java

  9. JTable • When we create a JTable we can have the user: • Edit the cells. • Select rows and columns whose data the user wants to save maybe in a file or in a data structure.

  10. Editing JTable • Example of EditableTable.java program on course ‘s web site. • Program lets user create a model object: • Override various methods of TableModel. • Calling the method fireTableCellUpdated(row, column) in turn calls the listener (event handler) of the Controller part. • Overriding method isCellEditable can identify the specific cells that the user can edit when the Table and its data is displayed. • Create the View: • Wrap the model object with a JTable object and then with a JScrollPane object. • Set the viewing size using the JTable object: Mytable.setPreferredScrollableViewportSize(new Dimension( 500, 300);

  11. Editing JTable • Create the Controller by implementing the Listener interface TableCellEditor and overriding its methods: public Component getTableCellEditorComponent (JTable table, Object value, boolean isSelected, int row, int column) and public Object getCellEditorValue() • Notice that editing can be done directly ion the displayed cell or on a special JTextArea or JTextField component that can be presented to the user.

  12. JTable –Selecting Rows and Columns. • See example SimpleTableSelectionDemo.java on the course’ s web site. • Create the model and view as in previous example of Editable Table. • Use the JTable object to set the mode of selection by the user” • Allow single row selection only or • Allow multiple rows to be selected or • Allow intervals of multiple rows to be selected. i.e table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); • Create a reference of ListSelectionModel and register it with an event handler. • The event handler overrides method valueChanged of ListSelectionListener interface. • In this method w e can sense the beginning index of the row selected and the ending index. • Once we know the rows we can capture the row data and do whatever we want to do with it.

  13. I/O Streams • Java uses many different types. Which stream you use depends on the type of communication i.e. • Are we opening a particular type of file for reading or writing? • What data types are involved? • Are we setting up a communication path between a client and a server? • Are we transmitting entire objects?

  14. File Types • Java basically supports two types of files: • text files: data is stored as characters • binary files: data is stored as raw bytes The type of a file is determined by the classes used to write to the file. • Types of Files can be: • Files written using Bytes Streams (1s and 0s). • Files written using Character Streams (char types). • Files written in terms of Strings (text). • Files written using primitive data types (int, double etc) • Files written using entire object streams (recording all information about an object in a coded format).

  15. File Types • To read an existing file, you must know the file's type in order to select and import the appropriate library classes for reading the file.

  16. Writing to Text Files • Several situations can exist: • the file does not exist • the file exists and we want to replace the current contents • the file exists and we want to append to the current contents • We specify whether we want to replace the contents or append to the current contents.

  17. Streams • Therefore: • To read a file input stream is needed. • To write to a file output stream is needed. • The java.io package provides the classes for establishing input and output streams.

  18. Selected Input Classes in the java.io Package

  19. Hierarchy for Input Classes

  20. Selected java.io Output Classes

  21. Hierarchy for Output Classes

  22. Reading Text Files with Scanner • In CS115 we used the File object and the Scanner object to read a text file • i.e. import java.io.File; import java.io.IOException; import java.util.Scanner; Public class ReadFile { Public static void main(String[] args) { try { File myfile=new File(“mytextfiel.txt”); Scanner scan=new Scanner(myfile); while(scan.hasMoreTokens()) { String str=scan.next(); System.out.println(str); } catch)(IOExceptionioe) { System.out.println(ioe.toString()); } } }

  23. Opening and Closing an Input Stream • When we construct an input stream or output stream object, the JVM associates the file name, standard input stream, or standard output stream with our object. This is opening the file. • When we are finished with a file, we optionally call the close method to release the resources associated with the file.

  24. Closing an output stream • When closing a Buffered output stream in addition to the close() method for the stream the methdod flush() should also be invoked: datastreamobject.flush(); • Flushing the output stream forces any buffered output bytes to be written out.

  25. Opening and Closing Standard Streams • Some streams are standard and the are available to any java program. • The standard input stream (System.in), the standard output stream (System.out), and the standard error stream (System.err) are open when the program begins.They are intended to stay open and should not be closed.

  26. Exceptions While Reading from a File We can catch this exception: FileNotFoundException thrown by the Scanner constructor if the filename is not found when opening the file We do not expect these exceptions to occur, so we will catch them as subclasses of IOException, and print the stack trace. InputMismatchException if the input does not match the expected data type. (The next method does not throw this exception, so we don’t need to catch this exception). NoSuchElementException if we attempt to read beyond the end of the file. IllegalStateException if we attempt to read after calling the close method.

  27. Buffering Writing data to the disk is much slower than writing data into main memory. When a class uses buffering, instead of writing one character at a time to the file, it accumulates the data in a temporary location in memory, called a buffer. When the buffer is full or is flushed, the accumulated data is written to the file in one efficient operation.

  28. Writing Primitive Types to Text Files FileOutputStream, a subclass of the OutputStream class, is designed to write a stream of bytes to a file. The PrintWriter class is designed for converting primitive data types to characters and writing them to an output stream. • print method, writes data without a newline • println method, writes data then adds a newline

  29. Example: Writing to a Text File Suppose we want to write a String aString to a File try { FileOutputStream file = new FileOutputStream(filename, true); OutputStreamWriter filestream = new OutputStreamWriter(new BufferedOutputStream(file)); filestream.write(aString); filestream.flush(); file.close(); } Catch(IOException ioe) { System.out.ptintln(ioe.toString()); } • If more than one String is to be written then a loop can be used. • Notice that the flush method needs to be called at the end to flush out the stream into the file. If this is not done the String is not written in the file!

  30. Serialization • Writing objects into a file involves a protocol of Java called: Serialization • Objects are converted (serialized) into a byte stream and stored in the file. • Reading objects from a file involves a protocol called deserialization. • Objects are converted back to the particular data type that they belong to.

  31. Serialization • A State of an object is the particular value sof its attributes (fields) at a particular time. • Saving a particular state via serialization is called “persistence”.

  32. Writing Objects to a File To write an object to a file, its class must implement the Serializable interface, which indicates that: • the object can be converted to a byte stream to be written to a file • that byte stream can be converted back into a copy of the object when read from the file TheSerializable interface has no methods to implement. All we need to do is: • import thejava.io.Serializable interface • add implementsSerializable to the class header • i.e public class MyClass implements Serializable

  33. The ObjectOutputStream Class The ObjectOutputStream class, coupled with the FileOutputStream class, provides the functionality to write objects to a file. The ObjectOutputStream class provides a convenient way to write objects to a file. • Its writeObject method takes one argument: the object to be written.

  34. Constructors for Writing Objects

  35. The writeObject Method

  36. Omitting Data from the File The writeObjectmethod does not write any object fields declared to be static or transient. You can declare a field as transient if you can easily reproduce its value or if its value is 0. Syntax to declare a field as transient: accessModifier transient dataTypefieldName Example: private transient double totalRevenue;

  37. Reading Objects from a File The ObjectInputStream class, coupled with FileInputStream, provides the functionality to read objects from a file. The readObject method of the ObjectInputStream class is designed to read objects from a file. Because the readObject method returns a generic Object,we must type cast the returned object to the appropriate class. When the end of the file is reached, the readObject method throws an EOFException, so we detect the end of the file when we catch that exception.

  38. Constructors for Reading Objects

  39. The readObject Method Note: • we detect reaching the end of the file in the EOFException catch block • we use a finally block to close the file

  40. Example Of Writing Objects • Suppose that we have a class called Vehicle. • We could serialize the Vehicle class by making a minor change to the class: public class Vehicle implements Serializable • We can exclude certain fields of the class from being serialized (and thus have their values written) by using the keyword transient in front of the declaration of the field. i.e. private transient double init_v; private transient double init_d;

  41. Example Of Writing Objects Vehicle va=new Vehicle(“My Vehicle”, 2, 3, 2.1, 3.5); try{ FileOutputStream fos=new FileOutputStream(“MyFile.ser”); ObjectOutputStream oos=new ObjectOutputStream(fos); oos.writeObject(va); oos.close(); } catch(IOException ioe) { System.out.println(“Error writing into file”); ioe.printStackTrace(); }

  42. Example of Reading the Object From the File try{ FileInputStreamfis = new FileInputStream(“MyFile.ser”); ObjectInputStreamois = new ObjectInputStream(fis); Vehicle vh = (Vehicle)ois.readObject(); ois.close(); } Catch(IOExceptionioe) { System.out.println(“Error writing into file”); ioe.printStackTrace(); } • We can output the object’s attributes and observe that the values are the same as the ones we wrote in the file.

  43. Client / Server • Socket: holds IP address and software port number number client server 1 Client’s Socket Listening Socket Data Port 2 • 1.Client contacts server’s listening port requesting permission to connect. • If permission is granted communications take place via a data port dedicated • to this client. • Other clients can request permission to connect and also be given their own • data port on the server.

  44. Client / Server • A multithreaded server handles each client communication with it in a separate thread for each client. • Networking can be established in Java by using the java.net classes. • In setting up the communications we can have two kinds of sockets : • Connection oriented: • Uses TCP/IP protocols. • Requires a handshake to establish the communication and a handshake to end it. • Reliable . Ensures that packets reach destination. • Continuous Stream sockets. • Think of it a s a phone call type of communication. • Connectionless oriented: • Uses datagram packets • Does not require a handshake to start the communication or to end it. • Unreliable. No guarantee that packets will arrive to their destination. • Better performance than TCP but requires more coding. • Think of it as writing a 10 page letter and putting it in 10 different envelops (one page in each envelop) and then mailing them.

  45. Client /Server • Three steps to create a Server process for TCP/IP: • Create a server socket object: ServerSocketss= new ServerSocket ( 5000, 100); Where 5000 is the listening port for the server and 100 is the maximum number of clients that can connect. ss object represents the listening socket • The following code lets the listening port to accept a request from a client: Socket connection=ss.accept();

  46. Client /Server • Notice that: • Program execution blocks at this line waiting for a client send connection request packets. • Socket type object connection encapsulates the information about the client when it arrives i.e. client’s IP address, client ‘s port number. • That when the server accepts it sends packets with information about itself including the port that is assigned to this client for data exchange. This port is assigned on the fly by the O.S. • Program execution now resumes. • Create input and Output Stream objects: ObjectInputStream input= new ObjectInputStream( connection.getInputStream()); //server gets input from client’s output stream ObjectOutputStream output=new ObjectOutputStream (connection.getOutputStream()); //server sends output out to the client’s input stream

  47. Client /Server • Notice that connection is the object that encapsulates the information about the particular client. • Use the object streams to either read incoming data from the Input Stream (on the port assigned to this particular client) or write into the Output Stream to send data to the client. i.e. Output.writeObject(String message); Or (String) input.readObject(); Notice that objects can be serialized and exchanged between the client and the server in a serializable format (streams of ones and zeros).

  48. Client /Server • Steps 2 and 3 should be in a while loop that lets the server run continually and block while it is waiting fro a client’s request. • The server should be started on its own DOS pane and then minimized letting it run in the background.

  49. Client / Server • Three steps to create a client process: • Create a Socket to ask connection with a server. Socket cs= new Socket(serverIP , port) Where serverIP is the IP address of the server (could be localhost if both client and server are on the same machine) and Port is the listening port number of the server (i.e. 5000 in our example). • Create Input and Output Stream objects as in step 3 of the server. i.e. ObjectOutputStream os= new ObjectOutputStream (cs.getOutputSream()); ObjectInputStream is= new ObjectInputStream (cs.getInputStream()); • Process incoming and outgoing data.

  50. Client / Server • See example on the course’s web site for client server processes. • Multithreaded Server: • Needs a main thread that allocates threads to clients requesting connection. This main thread passes to the allocated thread a reference of the Socket objec that represents the particular client from step 2 of the server example. • The allocated thread handles the subsequent communications between the client and the server by overriding the Thread class’ run method.

More Related