Question

In: Computer Science

In Simple Chat, if the server shuts down while a client is connected, the client does...

In Simple Chat, if the server shuts down while a client is connected, the client does not respond, and continues to wait for messages. Modify the client so that it responds to the shutdown of server by printing a message saying the server has shut down, and quitting. (look at the methods called connectionClosed and connectionException).

//ChatClient.java

// This file contains material supporting section 3.7 of the textbook:
// "Object Oriented Software Engineering" and is issued under the open-source
// license found at www.lloseng.com 

package client;

import ocsf.client.*;
import common.*;
import java.io.*;

/**
 * This class overrides some of the methods defined in the abstract
 * superclass in order to give more functionality to the client.
 *
 * @author Dr Timothy C. Lethbridge
 * @author Dr Robert Laganiè
 * @author François Bélanger
 * @version July 2000
 */
public class ChatClient extends AbstractClient
{
  //Instance variables **********************************************
  
  /**
   * The interface type variable.  It allows the implementation of 
   * the display method in the client.
   */
  ChatIF clientUI; 

  
  //Constructors ****************************************************
  
  /**
   * Constructs an instance of the chat client.
   *
   * @param host The server to connect to.
   * @param port The port number to connect on.
   * @param clientUI The interface type variable.
   */
  
  public ChatClient(String host, int port, ChatIF clientUI) 
    throws IOException 
  {
    super(host, port); //Call the superclass constructor
    this.clientUI = clientUI;
    openConnection();
  }

  
  //Instance methods ************************************************
    
  /**
   * This method handles all data that comes in from the server.
   *
   * @param msg The message from the server.
   */
  public void handleMessageFromServer(Object msg) 
  {
    clientUI.display(msg.toString());
  }

  /**
   * This method handles all data coming from the UI            
   *
   * @param message The message from the UI.    
   */
  public void handleMessageFromClientUI(String message)
  {
    try
    {
      sendToServer(message);
    }
    catch(IOException e)
    {
      clientUI.display
        ("Could not send message to server.  Terminating client.");
      quit();
    }
  }
  
  /**
   * This method terminates the client.
   */
  public void quit()
  {
    try
    {
      closeConnection();
    }
    catch(IOException e) {}
    System.exit(0);
  }
}
//End of ChatClient class

//EchoServer.java

// This file contains material supporting section 3.7 of the textbook:
// "Object Oriented Software Engineering" and is issued under the open-source
// license found at www.lloseng.com 

import java.io.*;
import ocsf.server.*;

/**
 * This class overrides some of the methods in the abstract 
 * superclass in order to give more functionality to the server.
 *
 * @author Dr Timothy C. Lethbridge
 * @author Dr Robert Laganière
 * @author François Bélanger
 * @author Paul Holden
 * @version July 2000
 */
public class EchoServer extends AbstractServer 
{
  //Class variables *************************************************
  
  /**
   * The default port to listen on.
   */
  final public static int DEFAULT_PORT = 5555;
  
  //Constructors ****************************************************
  
  /**
   * Constructs an instance of the echo server.
   *
   * @param port The port number to connect on.
   */
  public EchoServer(int port) 
  {
    super(port);
  }

  
  //Instance methods ************************************************
  
  /**
   * This method handles any messages received from the client.
   *
   * @param msg The message received from the client.
   * @param client The connection from which the message originated.
   */
  public void handleMessageFromClient
    (Object msg, ConnectionToClient client)
  {
    System.out.println("Message received: " + msg + " from " + client);
    this.sendToAllClients(msg);
  }
    
  /**
   * This method overrides the one in the superclass.  Called
   * when the server starts listening for connections.
   */
  protected void serverStarted()
  {
    System.out.println
      ("Server listening for connections on port " + getPort());
  }
  
  /**
   * This method overrides the one in the superclass.  Called
   * when the server stops listening for connections.
   */
  protected void serverStopped()
  {
    System.out.println
      ("Server has stopped listening for connections.");
  }
  
  //Class methods ***************************************************
  
  /**
   * This method is responsible for the creation of 
   * the server instance (there is no UI in this phase).
   *
   * @param args[0] The port number to listen on.  Defaults to 5555 
   *          if no argument is entered.
   */
  public static void main(String[] args) 
  {
    int port = 0; //Port to listen on

    try
    {
      port = Integer.parseInt(args[0]); //Get port from command line
    }
    catch(Throwable t)
    {
      port = DEFAULT_PORT; //Set port to 5555
    }
   
    EchoServer sv = new EchoServer(port);
    
    try 
    {
      sv.listen(); //Start listening for connections
    } 
    catch (Exception ex) 
    {
      System.out.println("ERROR - Could not listen for clients!");
    }
  }
}
//End of EchoServer class

//ChatIF.java

// This file contains material supporting section 3.7 of the textbook:
// "Object Oriented Software Engineering" and is issued under the open-source
// license found at www.lloseng.com 

package common;

/**
 * This interface implements the abstract method used to display
 * objects onto the client or server UIs.
 *
 * @author Dr Robert Laganière
 * @author Dr Timothy C. Lethbridge
 * @version July 2000
 */
public interface ChatIF 
{
  /**
   * Method that when overriden is used to display objects onto
   * a UI.
   */
  public abstract void display(String message);
}

//ClientConsole.java

// This file contains material supporting section 3.7 of the textbook:
// "Object Oriented Software Engineering" and is issued under the open-source
// license found at www.lloseng.com 

import java.io.*;
import client.*;
import common.*;

/**
 * This class constructs the UI for a chat client.  It implements the
 * chat interface in order to activate the display() method.
 * Warning: Some of the code here is cloned in ServerConsole 
 *
 * @author François Bélanger
 * @author Dr Timothy C. Lethbridge  
 * @author Dr Robert Laganière
 * @version July 2000
 */
public class ClientConsole implements ChatIF 
{
  //Class variables *************************************************
  
  /**
   * The default port to connect on.
   */
  final public static int DEFAULT_PORT = 5555;
  
  //Instance variables **********************************************
  
  /**
   * The instance of the client that created this ConsoleChat.
   */
  ChatClient client;

  
  //Constructors ****************************************************

  /**
   * Constructs an instance of the ClientConsole UI.
   *
   * @param host The host to connect to.
   * @param port The port to connect on.
   */
  public ClientConsole(String host, int port) 
  {
    try 
    {
      client= new ChatClient(host, port, this);
    } 
    catch(IOException exception) 
    {
      System.out.println("Error: Can't setup connection!"
                + " Terminating client.");
      System.exit(1);
    }
  }

  
  //Instance methods ************************************************
  
  /**
   * This method waits for input from the console.  Once it is 
   * received, it sends it to the client's message handler.
   */
  public void accept() 
  {
    try
    {
      BufferedReader fromConsole = 
        new BufferedReader(new InputStreamReader(System.in));
      String message;

      while (true) 
      {
        message = fromConsole.readLine();
        client.handleMessageFromClientUI(message);
      }
    } 
    catch (Exception ex) 
    {
      System.out.println
        ("Unexpected error while reading from console!");
    }
  }

  /**
   * This method overrides the method in the ChatIF interface.  It
   * displays a message onto the screen.
   *
   * @param message The string to be displayed.
   */
  public void display(String message) 
  {
    System.out.println("> " + message);
  }

  
  //Class methods ***************************************************
  
  /**
   * This method is responsible for the creation of the Client UI.
   *
   * @param args[0] The host to connect to.
   */
  public static void main(String[] args) 
  {
    String host = "";
    int port = 0;  //The port number

    try
    {
      host = args[0];
    }
    catch(ArrayIndexOutOfBoundsException e)
    {
      host = "localhost";
    }
    ClientConsole chat= new ClientConsole(host, DEFAULT_PORT);
    chat.accept();  //Wait for console data
  }
}
//End of ConsoleChat class

Do not know how to do for this question, could you give me some suggestions for that?

Solutions

Expert Solution

// start by running server code below

import java.io.*;
import java.net.*;
public class Server{
    public static final int DEFAULT_PORT = 6789;
    public static void main(String args[])throws IOException{
        Socket client;
        if(args.length !=1)
            client=accept(DEFAULT_PORT);
        else
            client=accept(Integer.parseInt(args[0]));
        shutdownServer(client);
    }

    /**
     * the method closes the server 
     * @param client
     */
    private static void shutdownServer(Socket client){
            //closing down the connection
        try {
            PrintWriter writer = new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
            writer.println("The server has shut down, and quitting");
            writer.flush();
            writer.close();
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * accepts the connection from the client
     * @param port
     * @return
     * @throws IOException
     */
    static Socket accept(int port)throws IOException{
        System.out.println("Starting on port" +port);
        ServerSocket server = new ServerSocket(port);
        System.out.println("waiting");
        Socket client = server.accept();
        System.out.println("Accepted from" +client.getInetAddress());
        server.close();
        return client;
    }
}

// the client side code is as shown below

import java.io.*;
import java.net.*;

/**
 * the client class
 */
public class Client{
    public static final int DEFAULT_PORT = 6789;
    public static void usage(){
        System.out.println("Usage: java C [<port>]");
        System.exit(0);
    }


    public static void main(String[] args){
        int port = DEFAULT_PORT;
        Socket socket = null;
        //parse the port specification
        if((args.length !=0) && (args.length !=1)) usage();
        if(args.length ==0) port = DEFAULT_PORT;
        else{
            try{
                port = Integer.parseInt(args[0]);
            }catch(NumberFormatException e){
                usage();
            }
        }
        try{
            BufferedReader reader;
            PrintWriter writer;
            //create a socket to communicate to the specified host and port
            socket = new Socket("localhost", port);
            //create streams for reading and writing
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));

            //tell the user that we've connect
            System.out.println("Connected to : " + socket.getInetAddress() + ":" + socket.getPort());
            //write a line to the server
            String line;
            writer.println("My message");
            writer.flush();
            //read the response (a line) from the server
            line = reader.readLine();

            //write the line to console
            System.out.println("Message from the server:" + line);
            reader.close();
            writer.close();
        }
        catch(IOException e){
            System.err.println(e.getMessage());
        }
        //always be sure to close the socket
        finally{
            try{
                if(socket != null) {
                    socket.close();
                }
            }catch (IOException e2){ }
        }
    }
}

The output:

The message below is thrown by the client after the server shuts down

_______________________________

Comment Down For Any Queries.

Please Give a Thumbs Up If You are satisfied With The Answer.


Related Solutions

what will be the code in C programming for the client and server chat application for...
what will be the code in C programming for the client and server chat application for the below issue :- write the C Programming code that able client have a unique ID to be known by the server
A limitation of the chat server is that it can handle only one client because it...
A limitation of the chat server is that it can handle only one client because it is a single threaded application. Using the pThread library, modify the chat server so that it can handle multiple clients simultaneously, i.e., by creating a new thread whenever a client is connected so that the client is handled individually with a new thread, and at the same time, by having the main thread (i.e., the thread that runs the main function) of the chat...
In the provided client and server code, the server can serve to single client at a...
In the provided client and server code, the server can serve to single client at a time. You have to change server.java code so that it can connect and serve multiple clients at the same time. Use multithreading. =============================================================================== import java.io.*; import java.net.*; public class Client { public static void main(String[] args) throws IOException { String serverHostname = new String ("127.0.0.1"); if (args.length > 0) { //pass the hsotname through cmd argument serverHostname = args[0]; } System.out.println ("Attemping to connect...
The client connects to the server. The server accepts the connection. The client sends a line...
The client connects to the server. The server accepts the connection. The client sends a line of text containing only SHAKESPEARE_COUNTS. The server sends back a sequence of integers. The number of integers in that list specifies the number of words in each insult; the numbers themselves specify how many possible words there are in each position. So, for example, if you received the output 15 20 30, it would indicate that insults are three words long, with 15 possible...
in Java - implement ftp-server and ftp-client. ftp-server Logging into ftp-server from ftp-client The ftp-server is...
in Java - implement ftp-server and ftp-client. ftp-server Logging into ftp-server from ftp-client The ftp-server is an interactive, command-line program that creates a server socket, and waits for connections. Once connected, the ftp-client can send and receive files with ftp-server until ftp-client logs out. Sending and receiving files The commands sent from the ftp-client to the ftp-server must recognize and handle are these: rename- the ftp-server responds to this command by renaming the named file in its current directory to...
How does the addition of computation on the server side and client side alter Sir Tim...
How does the addition of computation on the server side and client side alter Sir Tim Berners Lee’s original computational model?
13. If a firm shuts down in the short run and produces no output, its total...
13. If a firm shuts down in the short run and produces no output, its total cost will be a. zero b. equal to total variable cost c. equal to explicit costs only d. equal to total fixed costs e. equal to implicit costs only 14. The shape of the long-run average cost curve reflects a. the maximization of total product b. increasing and diminishing marginal returns c. economies and diseconomies of scale d. all of the above e. falling...
Explain why a firm only shuts down once the price drops to the minimum of the...
Explain why a firm only shuts down once the price drops to the minimum of the average variable cost (AVC) curve, rather than shutting down as soon as the price falls below the minimum of the average total cost (ATC) curve.
How do I make a simple TCP python web client and web server using only "import...
How do I make a simple TCP python web client and web server using only "import socket"? Basically, the client connects to the server, and sends a HTTP GET request for a specific file (like a text file, HTML page, jpeg, png etc), the server checks for the file and sends a copy of the data to the client along with the response headers (like 404 if not found, or 200 if okay etc). The process would be: You first...
1. How does TLS provide authentication? Does it provide mutual authentication (both client and server-side)? Is...
1. How does TLS provide authentication? Does it provide mutual authentication (both client and server-side)? Is that required? 2.What is the purpose of padding, Message Authentication Code (MAC), handshake protocol, change cyber suite (CCS) protocol? 3.How does TLS provide: confidentiality, availability, integrity, non-repudiation?
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT