FileDocCategorySizeDatePackage
SimpleClient.javaAPI DocExample2492Thu Oct 05 17:25:12 BST 2000None

SimpleClient.java

//File: SimpleClient.java

//loads classes needed for program
import java.io.*;
import java.net.*;

public class SimpleClient 
{
	//Ensures port number is same as server's
	public final static int DEF_PORT = SimpleServer.DEF_PORT;
	public final static String DEF_HOST = "localhost";

	private int port;
	public static String host=" ";

 public static void main(String[] args)
 {

 //creates input stream, allows input from keyboard
 DataInputStream userin = new DataInputStream(System.in);

 System.out.println("Enter host name(e.g. usun22)-");
 try
 {
 //reads host name entered by user
 host = userin.readLine();
 }

 //if host name is unreadable, terminate program
 catch(IOException inputhost)
 {
	System.out.println("Error reading host name");
	System.out.println("Exiting.........");
	System.exit(0);
 }

 //if no host entered assume host = local host
 if(host.length() < 1)
 {
 host=DEF_HOST;
 }

 try
 {
 	//create a socket connection using host name and server's port number
	Socket soc = new Socket(host, DEF_PORT);
	System.out.println("Connection established with host " + host);	
		
	//create an input and output stream for new connection
	PrintWriter outStream = new PrintWriter(new OutputStreamWriter(soc.getOutputStream()));
	BufferedReader inStream = new BufferedReader(new InputStreamReader(soc.getInputStream()));
	
	while(true)
	{
		System.out.println("-------------------------------------------");
		System.out.println("\nEnter Line to Send(Type 'quit' to quit)- ");
		
		//waits for user to input line of text	
		String toSend = userin.readLine();
		//send line of text to server
		outStream.println(toSend);
		//flust output stream
		outStream.flush();
		//if quit entered, close socket and terminate
		if (toSend.compareTo("quit")==0)
		{
			System.out.println("\n'quit' command entered by user");
			System.out.println("\nExiting...........\n");
			soc.close();
			System.exit(0);			
		}

	System.out.println("\nSent: " + toSend);

	//waits until reply received
	String reply = inStream.readLine();
		
	//displays reply
	System.out.println("\nReceived: " + reply);
 	}//end of while(true)

 }//end of try

 //caught if connection could not be established with host
 catch(IOException ex)
 {
	System.out.println("Connection failed due to host "+ host + " not responding");
	System.out.println("Exiting.......");
	System.exit(0);
 }
	
 }//end of main

}//end of SimpleClient