Monday, November 23, 2015

Responding program (server)

This program receives commands from a client and responds certain messages, See here for the client.

Code:

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class MyServer {
   public static void main(String args[]) {
      try {
         // Create a new server socket that listens at port 8080
         ServerSocket ServerSocket = new ServerSocket(8080);
         System.out.println("Server is lisenting ... ");
         Socket socket1 = ServerSocket.accept();//accept a connection from client on port 8080

         OutputStream outputStream1 = socket1.getOutputStream();
         ObjectOutputStream objectOutputStream1 = new ObjectOutputStream(outputStream1);
         InputStream inPutStream1 = socket1.getInputStream();
         ObjectInputStream objectInputStream1 = new ObjectInputStream(inPutStream1);

         String rcv_msg;
         while(true) {
            /* Recieve a message from client */
            System.out.println("Waiting for client to respond ... ");
            if((rcv_msg = (String)objectInputStream1.readObject()) != null) {
             if(rcv_msg.equals("What is your name?")){
              System.out.println("From Client : " + rcv_msg);
              System.out.print("\nTo Client : ");
                    objectOutputStream1.writeObject("My name is A.\n");
              continue;
             }else if(rcv_msg.equals("Song2")){
              System.out.println("From Client : " + rcv_msg);
              System.out.print("\nTo Client : ");
                    objectOutputStream1.writeObject("Woo-hooWoo-hoo\nWoo-hoo\nWoo-hoo");
              continue;
             }else if(rcv_msg.equals("What food do you like?")){
              System.out.println("From Client : " + rcv_msg);
              System.out.print("\nTo Client : ");
                    objectOutputStream1.writeObject("I like apples.\nWhat do you like to eat?\n");
              continue;
             }else{
              System.out.println("From Client : " + rcv_msg);
              System.out.print("\nTo Client : ");
                    objectOutputStream1.writeObject("Error.\n");
                    System.out.println("From Client : " + rcv_msg);
              continue;
             }
            }
         }
      } catch(Exception e) {
         System.out.println(e);
      }
   }
}