In: Computer Science
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?
// 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.