Monday, November 23, 2015

Responding program (client)

See here for the server program.

Code:

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
public class MyClient {
   public static void main(String args[]) {
      try {
         Socket theSocket = new Socket("write local IP address here", 8080);
         System.out.println("Connected to server");

         InputStream is = theSocket.getInputStream();
         ObjectInputStream ois = new ObjectInputStream(is);
         OutputStream os = theSocket.getOutputStream();
         ObjectOutputStream oos = new ObjectOutputStream(os);

         BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

         String rcv_msg, send_msg;
         while(true) {
            // Send a message to Server
            System.out.print("To Server : ");
            send_msg = br.readLine();
            oos.writeObject(send_msg);

            // Recieve a message from Server */
            System.out.println("Waiting for server to respond ... ");
            if((rcv_msg = (String)ois.readObject()) != null) {
               System.out.println("\nFrom Server : " + rcv_msg);
            }
         }
      } catch(Exception e) {
         System.out.println(e);
      }
   }
}