File size: 3,127 Bytes
7e59e4c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 | package Client;
/*
* Client.java
*/
import java.io.*;
import java.net.*;
import Common.*;
/**This is the main GUI class of the Client.
* The GUI should be built in this class.
*/
public class Client
{
/**This is the Network Component this Client GUI uses
* for sending and receiving messages.
*/
protected ClientNetwork myClientNetwork;
/**Constructor to build the Client.
* @param host The host which this client needs to connect to.
* @param port The port number where the host/server is listening.
*/
public Client(String host, int port)
{
this.myClientNetwork = new ClientNetwork(this, host, port);
String choice = "Y";
while (choice.trim().equals("y") || choice.trim().equals("Y"))
{
Message msg = new Message();
msg.readMessageFromKeyboard();
myClientNetwork.sendMessageToServer(msg);
System.out.println("\tWant to send Another Message(Y/N): " );
choice = getLine();
}
}
/**This method is called by the ClientNetwork whenever
* the ClientSocketReader receives a message from the server.
* @param msg The message which the client received from the server.
*/
public void gotMessageFromServer(Message msg)
{
showMessage("\nMESSAGE RECEIVED FROM THE SERVER: " + msg.printMessageDetails());
}
/**A small function to display messages.
* @param msg The message string to show.
*/
private static void showMessage(String msg)
{
System.err.println("Client: " + msg);
}
/**Gets a line from the keyboard.
* @return The line input by the user from the keyboard
*/
private String getLine()
{
BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in));
String line = null;
try
{
line = keyboard.readLine();
}
catch(IOException ioe)
{
showMessage("Error reading from keyboard.");
}
return line;
}
/**
* Main function which demonsrates the working of the Client class
* @param args[0] The name (or IP) of the host to connect to.
* @param args[1] The port number where the server is listening.
*/
public static void main(String[] args)
{
int port = 2000;
if (args.length < 1 || args.length > 2)
{
showMessage("Usage: java Client host_name port_number");
System.exit(1);
}
try
{
port = Integer.parseInt(args[1]);
}
catch (NumberFormatException e)
{
showMessage("Cannot Recognize Port Number...Defaulting to port " + port);
}
catch (IndexOutOfBoundsException iobe)
{
showMessage("Port Number not specified...Defaulting to port " + port);
}
Client myClient = new Client(args[0], port);
}
}
|