Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Programming in Java 6 with Swing and Servlets Part 1 Exercises: Networking Applications The easiest way to use networking inside an applet is to tell the browser running the applet to load a new page. Part One of this exercise creates links to new Web pages using the URL (Uniform Resource Locator) class. Different versions of the Java Virtual Machine may support different sets of URL protocols, but there is usually support for the http://, ftp:// and file:// protocols, and in Java 1.4l, secure HTTP is supported with the https:// protocol. Part One of this exercise will implement the client part of a client/server application. Part Two of this exercise will use a socket to communicate between a client and a server. The client will use the Socket class to connect with the server, and will access data from the server using the same methods and classes from the java.io package that were used to access data from a file. The server will use both the Socket class and the ServerSocket class to communicate with clients. The ServerSocket class allows the server to recognize and accept valid clients. Both the client and server will be implemented in this part of the exercise. Part One: Creating Links in Applets The URL class of the java.net package provides methods that an applet running on a remote system browser can call to link to Web pages existing on another server. Recall that the URL class represents a Uniform Resource Locator. One way to create a new URL object is directly from a URL string. The string should include the protocol, hostname, optional port name, and filename. URL myurl = new URL(“http://www.anywhere.com/”); If a program uses this type of constructor (creating a URL from a string), it must surround the constructor with a try/catch block in case a MalformedURLException occurs. After obtaining the URL, the applet only needs to pass it to the browser, by executing this command: getAppletContext().showDocument(myurl); The browser that contains the new URL will then load and display the document at that URL. 1. Create a new project directory: c:\labs\ModuleNine. Copyright ©2008, Custom Training Institute. All rights reserved. Networking Java Applications – Exercise: Page 2 2. Use you text editor to create a new Java application in the file BrowseURL.java that extends a Swing JApplet. 3. Change the layout of the applet to FlowLayout. Add a JList component to the Applet’s content pane. Set the selectionMode property of the JList to Single. 4. Add an inner class to describe the links that will be added to the JList component. Each object created from the class will consist of a String describing the link and a URL to access the link. Insert the following code inside the BrowseURL class: class LinkStore { private String title; private URL url; LinkStore(String title, URL url) { this.title = title; this.url = url; } public String getTitle() { return title; } public URL getURL() { return url; } public String toString() { return title; } } 5. Add the following class variables: private LinkStore[] myLinks = new LinkStore[7]; Copyright ©2008, Custom Training Institute. All rights reserved. Networking Java Applications – Exercise: Page 3 6. Import the following packages: import import import import import javax.swing.event.*; javax.swing.*; java.awt.*; java.net.*; java.applet.AppletContext; 7. Create the applet’s user interface in the getContentPanel() method. Add a ListSelectionListener to the JList. This listener will get the object selected from the JList, access the URL part of the object, and display it in the browser. Also add the code to create LinkStore objects and add them to the JList. private JPanel getMainPanel() { JPanel panel = new JPanel( new FlowLayout() ); panel.setBackground(Color.white); JList myJList = new JList(); myJList.setSelectionMode( javax.swing.ListSelectionModel.SINGLE_SELECTION); myJList.addListSelectionListener( new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { JList list = (JList) e.getSource(); LinkStore ls = (LinkStore) list.getSelectedValue(); getAppletContext().showDocument(ls.url); } }); myJList.setListData(myLinks); panel.add( myJList ); return panel; } 8. Create an array of LinkStore objects and store some URLs and a description in each object. Do this in the constructor. (You can create a list with fewer links if you wish, but remember to change the size of the LinkObject array to reflect the actual list size.) public BrowseURL() { super(); Copyright ©2008, Custom Training Institute. All rights reserved. Networking Java Applications – Exercise: Page 4 try { // create an array of LinkStore objects. URL url = new URL("http://www.google.com"); myLinks[0] = new LinkStore("Google", url ); url = new URL("http://java.sun.com"); myLinks[1] = new LinkStore("Sun's Java Site", url ); url = new URL("http://codeguru.earthweb.com/java"); myLinks[2] = new LinkStore("Java Programmer's Sourcebook", url ); url = new URL("http://www.afu.com/javafaq.html"); myLinks[3] = new LinkStore("Java Programmer' FAQ", url ); url = new URL("http://java.sun.com/products/jfc/tsc/index.html"); myLinks[4] = new LinkStore("The Swing Connection", url ); url = new URL("http://java.sun.com/products/jlf/at/book/"); myLinks[5] = new LinkStore("Java Look and Feed Design Guidelines", url ); url = new URL("http://www.javaworld.com/columns/jw-tips-index.shtml"); myLinks[6] = new LinkStore("Java Tips Index", url ); } catch (MalformedURLException e) { JOptionPane.showMessageDialog(this, e.getMessage(), "Malformed URL", JOptionPane.ERROR_MESSAGE); } setContentPane( getMainPanel() ); } 9. Save the files and compile the application. Once again we need an HTML page in which to embed the new applet. Create an html webpage, called c:\labs\ModuleNine\BrowseURL.html and place the following code in it: <HTML> <HEAD> <TITLE>BrowseURL</TITLE> </HEAD> <BODY> <h2>URL Library</h2> <APPLET code="BrowseURL.class" width="400" height="250"></APPLET> </BODY> </HTML> 10. Display the page in a web browser. Click one of the links in the list. The browser should display the new web page. Use the back button to return to the applet and click another link. The first image shown below is the initial display of the applet, Copyright ©2008, Custom Training Institute. All rights reserved. Networking Java Applications – Exercise: Page 5 and the second image is the display of Sun’s Java web page. This page was displayed when the first item in the list (Sun Java Site) was selected. Click on one of the links in the JList and you will be instructing the browser to move the current page to a new URL location. Copyright ©2008, Custom Training Institute. All rights reserved. Networking Java Applications – Exercise: Page 6 Part Two: Creating a Sockets Client/Server Clients and servers both use a Socket to communicate; however, a server must perform some additional tasks. A client establishes a single connection to a specific server, but the server must be able to recognize and accept connection requests from many clients. The server uses the ServerSocket class for this task. This networking exercise will show how to create a server that can handle multiple clients simultaneously by creating a separate Thread for each client connecting to it. The client will connect to a server by specifying both a specific internet address (127.0.0.1, or localhost, in this exercise) and a port number. A successful connection returns a Socket. Create the Server The server created in this exercise will perform the following steps: Create a ServerSocket object. Listen for a client to attempt a connection. Copyright ©2008, Custom Training Institute. All rights reserved. Networking Java Applications – Exercise: Page 7 Start a new Thread to handle the client Socket, allowing the server to listen for another client. The Thread will Get the OutputStream and InputStream, enabling the server to communicate with the client in the Thread Process the client requests by communicating via these streams in the Thread Close the connection when the client process is finished in the Thread 1. Create a new directory c:\labs\ModuleNineServer. 2. Create a new Java application in the file Server.java. Extend a Swing JFrame and create a main() method. Place the following code into main(). Server myServer = new Server(); myServer.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit( 0 ); } }); myServer.setVisible(true); myServer.process(); 3. Add an instance variable for the text area where the messages will be displayed with 20 rows and 40 columns. Add a variable to specify the port number to 5001 and one to set the number of requests in the backlog queue to 100. JTextArea clientInfo = new JTextArea(20, 40) public static final int PORT = 5001; public static final int NQUEUE = 100; 4. Add a JTextArea to the Center part of the frame’s BorderLayout. Set the following properties of the JTextArea: name = clientInfo rows = 20 columns = 40 Place the code to do this in the constructor as follows: public Server() { Copyright ©2008, Custom Training Institute. All rights reserved. Networking Java Applications – Exercise: Page 8 super("Socket Server"); getContentPane().add( new JScrollPane(clientInfo); setSize( 400,300 ); } 5. Add the following import statements before the class definition: import import import import import java.io.*; java.net.*; java.awt.*; java.awt.event.*; javax.swing.*; 6. Add an inner class that will be a Thread to handle each client that requests a connection to the server. Insert the following code just before the closing brace for the Server class: // Thread class to handle single client connection class ClientThread extends Thread { Socket client; ObjectOutputStream output; ObjectInputStream input; ClientThread(Socket client) { this.client = client; } public void run() { try { // Get input and output streams. output = new ObjectOutputStream( client.getOutputStream() ); output.flush(); input = new ObjectInputStream(client.getInputStream() ); clientInfo.append( "\nCreated I/O streams\n" ); // Process connection. String message = "Connection successful"; output.writeObject(message); output.flush(); do { try { message = (String) input.readObject(); Copyright ©2008, Custom Training Institute. All rights reserved. Networking Java Applications – Exercise: Page 9 sendData(message); clientInfo.append("\nReceived from Client: " + message + "\n"); clientInfo.setCaretPosition( clientInfo.getText().length()); } catch (ClassNotFoundException cnfex) { clientInfo.append("\nUnknown object type received\n"); } } while (!message.toUpperCase().equals("TERMINATE")); // Close connection. clientInfo.append("\nReceived TERMINATE: Closing connection.\n"); output.close(); input.close(); client.close(); } catch(Exception e) { System.err.println(e.getMessage()); } } private void sendData(String s) { try { output.writeObject(s); output.flush(); clientInfo.append("\nSent to Client: " + s + "\n"); } catch ( IOException cnfex ) { clientInfo.append("\nError writing object"); } } } 7. The above class will allow the server to communicate with multiple clients simultaneously. The run() method of the Thread establishes two streams: an output stream for sending messages to the client and an input stream for receiving messages from the client. A message is appended to the JTextArea field informing the user that the I/O streams were established. A message is then sent informing the client that the connection is successful. The thread enters a while loop that waits for the client to send input to the server. The server continues to read messages until it receives a message of the form “TERMINATE.” When the Copyright ©2008, Custom Training Institute. All rights reserved. Networking Java Applications – Exercise: Page 10 terminate message is received, the server closes the input and output streams and the Socket connection. All clients and servers must use a protocol in order to communicate. This exercise uses a very simple one. Each message sent from the client is a text string. The server simply echoes the client’s message back to the client. The only special command the server recognizes is the terminate request. Communication between the client and the server does not assume that either text or a stream of bytes will be sent to the input and output streams. Primitive data or generic objects might be sent, as well. To handle all possibilities, ObjectOutputStream and ObjectInputStream classes are used. Add the following method to the Server class. Make sure that you do not put it in the inner ClientThread class! public void process() { ServerSocket server; Socket client; int counter = 1; try { // Create a ServerSocket. server = new ServerSocket(PORT, NCLIENTS); clientInfo.setText( "\nCreated ServerSocket on Port: " + PORT + "for max of " + NCLIENTS + " connections\n"); while ( true ) { // Wait for a connection. clientInfo.setText("\nWaiting for connection\n"); client = server.accept(); clientInfo.append( "Connection " + counter + " received from: " + client.getInetAddress().getHostName()); // Create thread to handle this connection ClientThread t = new ClientThread(client); t.start(); counter++; } } catch ( Exception e) { System.err.println(e.getMessage()); } } Copyright ©2008, Custom Training Institute. All rights reserved. Networking Java Applications – Exercise: Page 11 8. The code above instantiates a ServerSocket object that registers an available port number of 5001 and a maximum number of clients that can request connections of 100. The server must use a port that no other services are using. (If there is any problem using 5001, which is usually safe, ask the instructor for a different port number.) Next, the server informs the user that it is waiting for a connection by writing text to the JTextArea, and it waits for a client to request a connection by calling the accept method in the ServerSocket class. The server blocks until a connection is accepted; at that point, it creates the Thread to handle the connection and calls its start() method. 9. Compile and run your application. You should see the window below, indicating the server is waiting for connections. If the port is in use by another application, you will see an error message. Exit the Server application. Create the Client The client is simpler than the server, and will implement the following steps: Create a Socket to connect to the server by specifying the server’s internet address and port number. A successful connection returns a Socket, which is connected to an InputStream and an OutputStream used to communicate with the server. Copyright ©2008, Custom Training Institute. All rights reserved. Networking Java Applications – Exercise: Page 12 The client uses these streams to communicate with the server. When the communication is finished, the client closes the connection. Client/server applications must use the same protocol, so that both can determine when the transmission is complete. 1. Create a new directory c:\labs\ModuleNineClient. 2. Create a new Java application called Client. Extend a Swing Jframe. add the main() method later. We will 3. Add a constructor as follows: public Client() { super("Socket Client"); setContentPane( getMainPanel() ); setSize( 400,300 ); } 4. Add code to create a GUI that does the following: a. Add a JTextArea to the Center part of the frame’s BorderLayout. Set the following properties of the JTextArea: i. ii. iii. name = serverInfo rows = 20 columns = 40 b. Add a JPanel to the North part of the frame’s BorderLayout. Make sure the JPanel has a FlowLayout setting and set its alignment set to Left. c. Add a JLabel to the JPanel in the North part of the frame. Set the text of the JLabel to “Enter message: “ d. Add a JTextField to the JPanel in the North part of the frame. Name the JTextField toServer and set the following properties: i. ii. iii. name = toServer enabled = false columns = 20 e. Data will be sent to the server when it is entered into the JTextField. To do this, an EventListener needs to be added to the toServer JTextField. Copyright ©2008, Custom Training Institute. All rights reserved. Networking Java Applications – Exercise: Page 13 5. The code that creates the GUI is shown below: private JPanel getMainPanel() { JPanel panel = new JPanel( new BorderLayout() ); serverInfo = new JTextArea(20, 40); serverInfo.setEditable(false); panel.add( new JScrollPane(serverInfo), BorderLayout.CENTER ); toServer = new JTextField(20); toServer.setEditable(false); toServer.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { sendData( e.getActionCommand()); } }); toServer.setEnabled(false); JPanel northPanel = new JPanel(new FlowLayout(FlowLayout.LEFT)); northPanel.add( new JLabel( "Enter message: " ) ); northPanel.add( toServer ); panel.add( northPanel, BorderLayout.NORTH ); return panel; } Note the use of the JScrollPane to enable the text area to scroll as neededs. 6. Add process() and sendData() methods similar to the ones added for the Server class. public void process() { Socket client; String message = ""; try { // Create a Socket to make connection. serverInfo.setText( "Attempting connection to : " + INETADDR + " on port: " + PORT); Copyright ©2008, Custom Training Institute. All rights reserved. Networking Java Applications – Exercise: Page 14 client = new Socket(InetAddress.getByName(INETADDR), PORT); serverInfo.append("\nConnected to: " + client.getInetAddress().getHostName()); // Get the input and output streams. output = new ObjectOutputStream(client.getOutputStream()); output.flush(); input = new ObjectInputStream(client.getInputStream()); serverInfo.append("\nI/O streams successfully created\n"); // Enable client to server input field for messages toServer.setEnabled(true); // Process the connection do { try { message = (String) input.readObject(); serverInfo.append("\n[from server] "+message+"\n"); serverInfo.setCaretPosition(serverInfo.getText().length()); } catch (ClassNotFoundException cnfex) { serverInfo.append("\nUnknown object type received\n"); } } while (!message.toUpperCase().equals("TERMINATE")); toServer.setEnabled(false); serverInfo.setEnabled(false); // Close connection. serverInfo.append("\nReceived TERMINATE: Closing connection.\n"); output.close(); input.close(); client.close(); } catch (EOFException eof) { System.out.println("\nServer terminated connection"); Copyright ©2008, Custom Training Institute. All rights reserved. Networking Java Applications – Exercise: Page 15 } catch (IOException e) { e.printStackTrace(); } } private void sendData(String s) { try { output.writeObject(s); output.flush(); serverInfo.append("\nSent from Client to Server:" + s); } catch (IOException cnfex) { serverInfo.append("\nError writing object"); } } 7. Add the following as class variables: private private private private final int PORT = 5001; final String INETADDR = "127.0.0.1"; ObjectOutputStream output; ObjectInputStream input; 8. Add the following import statements before the class definition: import import import import import java.io.*; java.net.*; java.awt.*; java.awt.event.*; javax.swing.*; 9. Instantiate a Client object in the main() method, add a listener to close the application, and run the client. Client app = new Client(); app.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { Copyright ©2008, Custom Training Institute. All rights reserved. Networking Java Applications – Exercise: Page 16 System.exit( 0 ); } }); app.setVisible(true); app.process(); 10. Save the files and compile the application. 11. Run the client application. The window should contain the message “Attempting connection,” but there will be “Connection Refused” error shown in the text area because the server is not running. Exit the client application. 12. Test the client/server application by starting the server. The Server window will open and display the message “Waiting for connection.” Start the client and the Client window will open and display the message “Attempting connection.” Both windows should indicate they have I/O streams, and the server should send a “Connection successful” message to the client. The server application, Copyright ©2008, Custom Training Institute. All rights reserved. Networking Java Applications – Exercise: Page 17 The Client application, 13. Enter First Message: Hello into the top text field, then press the <Enter> key. The Server window should indicate that the text was received, and the echo should appear in the Client window. The server responds the reception of the message: Copyright ©2008, Custom Training Institute. All rights reserved. Networking Java Applications – Exercise: Page 18 14. Enter TerMinaTE into the Client window to end communication between the client and the server. The windows below reflect the result. The server responds: 15. The string is converted to upper case before being compared to the ending TERMINATE string, allowing the user to type any combination of upper and lower case characters. To verify that the server can handle more than one connection, start multiple clients before closing all windows. Copyright ©2008, Custom Training Institute. All rights reserved. Networking Java Applications – Exercise: Page 19 Solution BrowseURL.java import javax.swing.event.*; import javax.swing.*; import java.awt.*; import java.net.*; import java.applet.AppletContext; /** * Module 8: An applet that interacts with a web browser. */ public class BrowseURL extends JApplet { /** links and a link descriptin are stored in this array */ private LinkStore[] myLinks = new LinkStore[7]; /** * zero-argument constructor that creates the array of links * and creates the GUI. */ public BrowseURL() { super(); try { // create an array of LinkStore objects. URL url = new URL("http://www.google.com"); myLinks[0] = new LinkStore("Google", url ); url = new URL("http://java.sun.com"); myLinks[1] = new LinkStore("Sun's Java Site", url ); url = new URL("http://codeguru.earthweb.com/java"); myLinks[2] = new LinkStore("Java Programmer's Sourcebook", url ); url = new URL("http://www.afu.com/javafaq.html"); myLinks[3] = new LinkStore("Java Programmer' FAQ", url ); url = new URL("http://java.sun.com/products/jfc/tsc/index.html"); myLinks[4] = new LinkStore("The Swing Connection", url ); url = new URL("http://java.sun.com/products/jlf/at/book/"); myLinks[5] = new LinkStore("Swing Examples", url ); url = new URL("http://www.javaworld.com/columns/jw-tips-index.shtml"); myLinks[6] = new LinkStore("Java Tips Index", url ); } catch (MalformedURLException e) Copyright ©2008, Custom Training Institute. All rights reserved. Networking Java Applications – Exercise: Page 20 { JOptionPane.showMessageDialog(this, e.getMessage(), "Malformed URL", JOptionPane.ERROR_MESSAGE); } setContentPane( getMainPanel() ); } /** * constructs the primary GUI panel. */ private JPanel getMainPanel() { JPanel panel = new JPanel( new FlowLayout() ); panel.setBackground(Color.white); JList myJList = new JList(); myJList.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION); myJList.addListSelectionListener(new ListSelectionListener() { public void valueChanged(ListSelectionEvent e) { JList list = (JList) e.getSource(); LinkStore ls = (LinkStore) list.getSelectedValue(); getAppletContext().showDocument(ls.url); } }); myJList.setListData(myLinks); panel.add( myJList ); return panel; } /** * init stub -- not used. */ public void init() { } /** * Store a set of name-value pairs representing a Copyright ©2008, Custom Training Institute. All rights reserved. Networking Java Applications – Exercise: Page 21 * URL and its description. */ class LinkStore { /** a description of the URL */ private String title; /** a link */ private URL url; /** * Create a LinkStore and initialize its URL and * description. * @param title a description of the link. * @param url the address of the link. */ LinkStore(String title, URL url) { this.title = title; this.url = url; } /** @return the description of the link */ public String getTitle() { return title; } /** @return the link */ public URL getURL() { return url; } /** @return a representative string for this object */ public String toString() { return title; } } } Copyright ©2008, Custom Training Institute. All rights reserved. Networking Java Applications – Exercise: Page 22 BrowseURL.html <HTML> <HEAD> <TITLE>BrowseURL</TITLE> </HEAD> <BODY> <h2 align="center">URL Library</h2> <APPLET code="BrowseURL.class" width="400" height="200"></APPLET> <p><i>Note: The background color of the applet has been set to the background color of this web page. </p> </BODY> </HTML> Server.java import java.io.*; import java.net.*; import java.awt.event.*; import javax.swing.*; /** * Module 8: A simple socket server example. This server is able * to receive java objects sent from a client application. To * terminate the service from the client, send the "terminate" * string. */ public class Server extends JFrame { /** the conversation with the client is displayed here */ JTextArea clientInfo = new JTextArea(20, 40); /** the server will listen on this port number */ public static final int PORT = 5001; /** the server can handle this many clients */ public static final int NQUEUE = 100; /** * Zero-argument constructor creates a new Server and * initializes its GUI. Copyright ©2008, Custom Training Institute. All rights reserved. Networking Java Applications – Exercise: Page 23 */ public Server() { super("Socket Server"); getContentPane().add( new JScrollPane(clientInfo) ); setSize( 400,300 ); } /** * process requests from the client and send a server response. */ public void process() { ServerSocket server; Socket client; int counter = 1; try { // Create a ServerSocket. server = new ServerSocket(PORT, NQUEUE); clientInfo.setText( "\nCreated ServerSocket on Port: " + PORT + " for queue of " + NQUEUE + " connections\n"); while ( true ) { // Wait for a connection. clientInfo.append("\nWaiting for connection\n"); client = server.accept(); clientInfo.append( "Connection " + counter + " received from: " + client.getInetAddress().getHostName()); // Create thread to handle this connection ClientThread t = new ClientThread(client); t.start(); counter++; } } catch ( Exception e) { System.err.println(e.getMessage()); } } Copyright ©2008, Custom Training Institute. All rights reserved. Networking Java Applications – Exercise: Page 24 /** * Thread class to handle a single client connection. */ class ClientThread extends Thread { Socket client; ObjectOutputStream output; ObjectInputStream input; ClientThread(Socket client) { this.client = client; } public void run() { try { // Get input and output streams. output = new ObjectOutputStream(client.getOutputStream() ); output.flush(); input = new ObjectInputStream(client.getInputStream() ); clientInfo.append( "\nCreated I/O streams\n" ); // Process connection. String message = "Connection successful"; output.writeObject(message); output.flush(); do { try { message = (String) input.readObject(); sendData(message); clientInfo.append("\nReceived from Client: " + message + "\n"); clientInfo.setCaretPosition(clientInfo.getText().length()); } catch (ClassNotFoundException cnfex) { clientInfo.append("\nUnknown object type received\n"); } } while (!message.toUpperCase().equals("TERMINATE")); Copyright ©2008, Custom Training Institute. All rights reserved. Networking Java Applications – Exercise: Page 25 // Close connection. clientInfo.append("\nReceived TERMINATE: Closing connection.\n"); output.close(); input.close(); client.close(); } catch(Exception e) { System.err.println(e.getMessage()); } } private void sendData(String s) { try { output.writeObject(s); output.flush(); clientInfo.append("\nSent to Client: " + s + "\n"); } catch ( IOException cnfex ) { clientInfo.append("\nError writing object"); } } } /** * Start the socket server application. */ public static void main( String[] args ) { Server myServer = new Server(); myServer.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit( 0 ); } }); myServer.setVisible(true); myServer.process(); Copyright ©2008, Custom Training Institute. All rights reserved. Networking Java Applications – Exercise: Page 26 } } Client.java import java.io.*; import java.net.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; /** * Module 8: A simple socket client example. This client will * connect with this module's server and interact with a user * to send strings to the server and print the server's response * to a text area. */ public class Client extends JFrame { /** the client will connect to a server listening on this port */ private static final int PORT = 5001; /** the client will connect to a server on this host */ private static final String INETADDR = "127.0.0.1"; /** the server's response is printed to this text area */ JTextArea serverInfo; /** Strings entered into this text field are sent to the server */ JTextField toServer; /** The server's response arrives on this stream */ ObjectInputStream input; /** The client's requests are sent on this stream */ ObjectOutputStream output; /** * zero-argument constructor creates the clients gui. */ public Client() { super("Socket Client"); setContentPane( getMainPanel() ); Copyright ©2008, Custom Training Institute. All rights reserved. Networking Java Applications – Exercise: Page 27 setSize( 400,300 ); } /** * Create the client's main panel. */ private JPanel getMainPanel() { JPanel panel = new JPanel( new BorderLayout() ); serverInfo = new JTextArea(20, 40); serverInfo.setEditable(false); panel.add( new JScrollPane(serverInfo), BorderLayout.CENTER ); toServer = new JTextField(20); toServer.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { sendData( e.getActionCommand()); } }); toServer.setEnabled(false); JPanel northPanel = new JPanel( new FlowLayout( FlowLayout.LEFT ) ); northPanel.add( new JLabel( "Enter message: " ) ); northPanel.add( toServer ); panel.add( northPanel, BorderLayout.NORTH ); return panel; } /** * Loops sending user input to the server and processing server * responses. */ public void process() { Socket client; String message = ""; try { // Create a Socket to make connection. Copyright ©2008, Custom Training Institute. All rights reserved. Networking Java Applications – Exercise: Page 28 serverInfo.setText( "Attempting connection to : " + INETADDR + " on port: " + PORT); client = new Socket(InetAddress.getByName(INETADDR), PORT); serverInfo.append("\nConnected to: " + client.getInetAddress().getHostName()); // Get the input and output streams. output = new ObjectOutputStream(client.getOutputStream()); output.flush(); input = new ObjectInputStream(client.getInputStream()); serverInfo.append("\nI/O streams successfully created\n"); // Enable client to server input field for messages toServer.setEnabled(true); // Process the connection do { try { message = (String) input.readObject(); serverInfo.append("\n[from server] " + message + "\n"); serverInfo.setCaretPosition(serverInfo.getText().length()); } catch (ClassNotFoundException cnfex) { serverInfo.append("\nUnknown object type received\n"); } } while (!message.toUpperCase().equals("TERMINATE")); toServer.setEnabled(false); serverInfo.setEnabled(false); // Close connection. serverInfo.append("\nReceived TERMINATE: Closing connection.\n"); output.close(); input.close(); client.close(); } catch (EOFException eof) { serverInfo.append( "\nServer terminated connection"); } Copyright ©2008, Custom Training Institute. All rights reserved. Networking Java Applications – Exercise: Page 29 catch (IOException e) { serverInfo.append( "\n*** ERROR ***\n" + e.getMessage() ); } } /** * Send a string to the server. */ private void sendData(String s) { try { output.writeObject(s); output.flush(); serverInfo.append("\n> " + s); } catch (IOException cnfex) { serverInfo.append("\nError writing object"); } } /** * run the client application. */ public static void main( String[] args ) { Client myClient = new Client(); myClient.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit( 0 ); } }); myClient.setVisible(true); myClient.process(); } } Copyright ©2008, Custom Training Institute. All rights reserved. Networking Java Applications – Exercise: Page 30 Copyright ©2008, Custom Training Institute. All rights reserved.