diff --git a/code/simplechat1/ClientConsole.java b/code/simplechat1/ClientConsole.java index c9bb4e9..0a6f4f1 100644 --- a/code/simplechat1/ClientConsole.java +++ b/code/simplechat1/ClientConsole.java @@ -16,13 +16,13 @@ * @author Dr Robert Laganière * @version July 2000 */ -public class ClientConsole implements ChatIF -{ +public class ClientConsole implements ChatIF { //Class variables ************************************************* /** * The default port to connect on. */ + final public static int DEFAULT_PORT = 5555; //Instance variables ********************************************** @@ -41,11 +41,11 @@ public class ClientConsole implements ChatIF * @param host The host to connect to. * @param port The port to connect on. */ - public ClientConsole(String host, int port) + public ClientConsole(String loginID, String host, int port) { try { - client= new ChatClient(host, port, this); + client= new ChatClient(loginID, host, port, this); } catch(IOException exception) { @@ -104,18 +104,43 @@ public void display(String message) */ public static void main(String[] args) { - String host = ""; + String loginID = ""; + String host = ""; int port = 0; //The port number - + + // User-specified login ID try { - host = args[0]; + loginID = args[0]; } + // No user-specified login ID given + catch(ArrayIndexOutOfBoundsException e) + { + System.out.println("Error. No login ID given. Exiting."); + System.exit(1); // Not an intentional attempt to exit, so error code 1 + } + + // User-specified host name + try + { + host = args[1]; + } + // Default host name catch(ArrayIndexOutOfBoundsException e) { host = "localhost"; } - ClientConsole chat= new ClientConsole(host, DEFAULT_PORT); + + // User-specified port number + try { + port = Integer.parseInt(args[2]); + } + // Default port number + catch(ArrayIndexOutOfBoundsException e) { + port = DEFAULT_PORT; + } + + ClientConsole chat= new ClientConsole(loginID, host, port); chat.accept(); //Wait for console data } } diff --git a/code/simplechat1/EchoServer.java b/code/simplechat1/EchoServer.java index d4f3a1a..294dc88 100644 --- a/code/simplechat1/EchoServer.java +++ b/code/simplechat1/EchoServer.java @@ -15,8 +15,7 @@ * @author Paul Holden * @version July 2000 */ -public class EchoServer extends AbstractServer -{ +public class EchoServer extends AbstractServer{ //Class variables ************************************************* /** @@ -31,13 +30,27 @@ public class EchoServer extends AbstractServer * * @param port The port number to connect on. */ - public EchoServer(int port) - { + public EchoServer(int port) { super(port); } - //Instance methods ************************************************ + + // When an exception of a client occurs + public void clientException(ConnectionToClient client) { + System.out.println("An exception occured."); + clientDisconnected(client); + } + + // When a client connects + public void clientConnected(ConnectionToClient client) { + System.out.println("A client is now connected."); + } + + // When a client disconnects + public void clientDisconnected(ConnectionToClient client) { + System.out.println("A client is now disconnected."); + } /** * This method handles any messages received from the client. @@ -45,31 +58,118 @@ public EchoServer(int port) * @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); + public void handleMessageFromClient(Object msg, ConnectionToClient client) { + String stringMsg = (String) msg; + String[] splitMsg = stringMsg.split(" "); + if (splitMsg[0].equals("#login")) { + if (splitMsg.length > 1) { + // loginID is not yet defined + if (client.getInfo("loginID") == null) { + client.setInfo("loginID", splitMsg[1]); + sendToAllClients(splitMsg[1] + " logged in."); + } + // loginID is already defined + else { + try { + client.sendToClient("Error. " + splitMsg[1] + " is already logged in."); + client.close(); + } + catch (IOException e) { + System.out.println("Unexpected error while attempting to log in."); + } + } + } else { + try { + client.sendToClient("Error. Must define login ID."); + } + catch (IOException e) { + System.out.println("Unexpected error while attempting to log in."); + } + } + } + // Server echoes each message to all clients + else { + System.out.println("Message received: " + msg + " from " + client); + this.sendToAllClients(client.getInfo("loginID") + " : " + msg); + } } + + /** + * This method handles any messages received from the server. + * + * @param msg The message received from the server. + */ + public void handleMessageFromServer(String message) { + // Anything starting with "#" is considered to be a command + if (message.startsWith("#")) { + String[] splitMsg = message.split(" "); + switch (splitMsg[0]) { + // Server terminates gracefully + case "#quit": + System.out.println("Commanded to quit."); + System.exit(0); // Exit is intentional, so error code of 0 + break; + // Server stops listening for new clients + case "#stop": + System.out.println("Commanded to stop."); + stopListening(); + break; + // Server stops listening for new clients and disconnects all existing clients + case "#close": + System.out.println("Commanded to close."); + stopListening(); + try { + close(); + } + catch (IOException e) {} + break; + // Sets server port number for next connection, but only if server is closed + case "#setport": + if (!isListening()) { + System.out.println("Commanded to set port."); + setPort(Integer.parseInt(splitMsg[1])); + } else { + System.out.println("Error. Cannot set port because the server is not closed."); + } + break; + // Server starts listening for new clients, but only if server is stopped + case "#start": + if (!isListening()) { + System.out.println("Commanded to start."); + try { + listen(); + } + catch (IOException e) {} + } else { + System.out.println("Error. Cannot start because the server is not stopped."); + } + break; + // Display current port number + case "#getport": + System.out.println("Port number: " + getPort()); + break; + // Command not recognized + default: + System.out.println("Command not recognized"); + break; + } + } + } /** * 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()); + 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."); + protected void serverStopped() { + System.out.println("Server has stopped listening for connections."); } //Class methods *************************************************** @@ -81,27 +181,22 @@ protected void serverStopped() * @param args[0] The port number to listen on. Defaults to 5555 * if no argument is entered. */ - public static void main(String[] args) - { + public static void main(String[] args) { int port = 0; //Port to listen on - try - { + try { port = Integer.parseInt(args[0]); //Get port from command line } - catch(Throwable t) - { + catch(Throwable t) { port = DEFAULT_PORT; //Set port to 5555 } - EchoServer sv = new EchoServer(port); + ServerConsole sc = new ServerConsole(port); - try - { - sv.listen(); //Start listening for connections + try { + sc.accept(); } - catch (Exception ex) - { + catch (Exception ex) { System.out.println("ERROR - Could not listen for clients!"); } } diff --git a/code/simplechat1/ServerConsole.java b/code/simplechat1/ServerConsole.java new file mode 100644 index 0000000..9d6f7c8 --- /dev/null +++ b/code/simplechat1/ServerConsole.java @@ -0,0 +1,50 @@ +// ServerConsole class allows user input directly into the server's console, then +// echoes the input to all clients + +import java.io.*; +import common.*; + +public class ServerConsole implements ChatIF{ + final public static int DEFAULT_PORT = 5555; + EchoServer server; + public ServerConsole(int port) { + server = new EchoServer(port); + try { + server.listen(); + } + catch(IOException exception) { + System.out.println("Error: Can't setup connection!" + + " Terminating client."); + System.exit(1); + } + } + public void accept() { + try { + BufferedReader fromConsole = new BufferedReader(new InputStreamReader(System.in)); + String message; + while (true) { + message = fromConsole.readLine(); + server.handleMessageFromServer(message); + display(message); + } + } + catch (Exception ex) { + System.out.println("Unexpected error while reading from console!"); + } + } + public void display(String message) { + System.out.println("SERVER MSG > " + message); + } + 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 + } + ServerConsole sc = new ServerConsole(port); + sc.accept(); + } +} +// End of ServerConsole class \ No newline at end of file diff --git a/code/simplechat1/client/ChatClient.java b/code/simplechat1/client/ChatClient.java index fe1401e..f103c43 100644 --- a/code/simplechat1/client/ChatClient.java +++ b/code/simplechat1/client/ChatClient.java @@ -17,16 +17,14 @@ * @author François Bélanger * @version July 2000 */ -public class ChatClient extends AbstractClient -{ +public class ChatClient extends AbstractClient { //Instance variables ********************************************** /** * The interface type variable. It allows the implementation of * the display method in the client. */ - ChatIF clientUI; - + ChatIF clientUI; //Constructors **************************************************** @@ -38,51 +36,105 @@ public class ChatClient extends AbstractClient * @param clientUI The interface type variable. */ - public ChatClient(String host, int port, ChatIF clientUI) - throws IOException - { + public ChatClient(String loginID, String host, int port, ChatIF clientUI) throws IOException { super(host, port); //Call the superclass constructor this.clientUI = clientUI; - openConnection(); + openConnection(); + sendToServer("#login " + loginID); } //Instance methods ************************************************ + /** + * This method handles all data coming from the UI + * + * @param message The message from the UI. + */ + public void handleMessageFromClientUI(String message) { + // Anything starting with "#" is considered to be a command + if (message.startsWith("#")) { + String[] splitMsg = message.split(" "); + switch (splitMsg[0]) { + // Client terminates gracefully + case "#quit": + System.out.println("Commanded to quit."); + quit(); + break; + // Client disconnects from server, but not quit the program + case "#logoff": + System.out.println("Commanded to log off."); + try { + closeConnection(); + } + catch (IOException e) { + System.out.println("Error. Cannot log off."); + } + break; + // Sets server host for next connection, but only if client is logged off + case "#sethost": + if (!isConnected()) { + System.out.println("Commanded to set host."); + setHost(splitMsg[1]); + } else { + System.out.println("Error. Cannot set host because the client is still logged on."); + } + break; + // Sets server port number for next connection, but only if client is logged off + case "#setport": + if (!isConnected()) { + System.out.println("Commanded to set port."); + setPort(Integer.parseInt(splitMsg[1])); + } else { + System.out.println("Error. Cannot set port because the client is still logged on."); + } + break; + // Connects client to server, but if not already connected + case "#login": + try { + System.out.println("Commanded to log in."); + openConnection(); + } catch (IOException e) { + System.out.println("Error. Cannot connect client to server because they are already connected."); + } + break; + // Display current host name + case "#gethost": + System.out.println("Host name: " + getHost()); + break; + // Display current port number + case "#getport": + System.out.println("Port number: " + getPort()); + break; + // Command not recognized + default: + System.out.println("Command not recognized"); + break; + } + } else { + try { + sendToServer(message); + } + catch(IOException e) { + clientUI.display + ("Could not send message to server. Terminating client."); + quit(); + } + } + } /** * This method handles all data that comes in from the server. * * @param msg The message from the server. */ - public void handleMessageFromServer(Object msg) - { + 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() - { + public void quit() { try { closeConnection(); @@ -90,5 +142,17 @@ public void quit() catch(IOException e) {} System.exit(0); } + + // The connection is closed + public void connectionClosed() { + System.out.println("Connection closed."); + } + + // Exception handling if connection is closed + public void connectionException(Exception exception) { + System.out.println("Connection error: server closed. Closing program."); + quit(); // Exits the program gracefully + } + } //End of ChatClient class