Saturday, December 24, 2011

QTPGridClient.java.txt

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class QTPGridClient{
    Socket requestSocket;
    ObjectOutputStream out;
     ObjectInputStream in;
     String message;
    static String Msg;
    static String IPAdd;
    QTPGridClient(){}
    void run()
    {
        try{
            //1. creating a socket to connect to the server
            requestSocket = new Socket(IPAdd, 2004);
            System.out.println("Connected to " + IPAdd);
            //2. get Input and Output streams
            out = new ObjectOutputStream(requestSocket.getOutputStream());
            out.flush();
            in = new ObjectInputStream(requestSocket.getInputStream());
            //3: Communicating with the server
            try{
                message = (String)in.readObject();
                System.out.println("server>" + message);
                sendMessage(Msg);
                message = (String)in.readObject();
                System.out.println("server>" + message);
                sendMessage("Terminate Connection");
            }catch(ClassNotFoundException classNot){
                System.err.println("Error: data received in unknown format");
            }
           
        }catch(UnknownHostException unknownHost){
            System.err.println("Error: You are trying to connect to an unknown host!");
        }catch(IOException ioException){
            System.err.println("Error: Server might not be running on: " + IPAdd);
            //ioException.printStackTrace();
        }
        finally{
            //4: Closing connection
            try{
                in.close();
                out.close();
                requestSocket.close();
            }catch(IOException ioException){
                //ioException.printStackTrace();
            }
        }
    }
    void sendMessage(String msg)
    {
        try{
            out.writeObject(msg);
            out.flush();
            //System.out.println("client>" + msg);
        }
        catch(IOException ioException){
            //ioException.printStackTrace();
        }
    }
    public static void main(String args[])
    {
        try{
            IPAdd = args[0];
            Msg = args[1];
            QTPGridClient client = new QTPGridClient();
            client.run();
            System.out.println("Exiting Program..");
        }catch(Exception e){
            System.err.println("Error: Unable to send message. Terminating Program!!");
        }
    }
}

No comments:

Post a Comment