Interviews Questions, Algorithms, Aptitude, C Interview Program, C Theory Question, Aptitude Tricks, Test Series,

Tuesday 9 April 2019

TCP Factorial Without Modification

Question Label Internal 5 TCP 
Write a Java program to implement client-server interaction using connection-oriented sockets. 
 The client must send a number to a server as a request. The server must process the request  as a thread and return the factorial of the requested number as a response to the client.
   If a negative number is sent from the client, the server must throw a user-defined exceptionnamed NegativeNumberException.


Server Side

// Java implementation of  Server side 
// It contains two classes : Server and ClientHandler 
// Save file as factserver.java 
//Run it First
  
import java.io.*; 
import java.text.*; 
import java.util.*; 
import java.net.*; 
//Exception Class
class NegativeNumberException extends Exception {
private String op;

   public NegativeNumberException(String op) {
this.op = op;
}

public String toString() {
return "NegativeNumberException: Operation Factorial is Denied by server";

}

}

// Server class 
public class factserver  

    public static void main(String[] args) throws IOException  
    { 
        // server is listening on port 5060 
        ServerSocket ss = new ServerSocket(5060); 
          
        // running infinite loop for getting 
        // client request 
        while (true)  
        { 
            Socket s = null; 
              
            try 
            { 
                // socket object to receive incoming client requests 
                s = ss.accept(); 
                     
                // obtaining input and out streams 
         DataInputStream dis = new DataInputStream(s.getInputStream()); 
         DataOutputStream dos = new DataOutputStream(s.getOutputStream()); 
                  
                // create a new thread object 
                Thread t = new ClientHandler(s, dis, dos); 
  
                // Invoking the start() method 
                t.start(); 
                  
            } 
            catch (Exception e){ 
                s.close(); 
                e.printStackTrace(); 
            } 
        } 
    } 

  
// ClientHandler class 
class ClientHandler extends Thread  {   
    final DataInputStream dis; 
    final DataOutputStream dos; 
    final Socket s; 
      
  
    // Constructor 
 public ClientHandler(Socket s, DataInputStream dis, DataOutputStream dos)  
    { 
        this.s = s; 
        this.dis = dis; 
        this.dos = dos; 
    } 
  
    @Override
    public void run()  
    {  
        String received; 
        String toreturn; 
     int num,count = 1;
     while (true)     { 
            try { 
  
                // Ask user what he wants 
          dos.writeUTF("Press any number to get Factorial..\n"+"or"+ 
                            "Type Exit to terminate connection."); 
                  
                // receive the answer from client 
                received = dis.readUTF(); 
                  
                if(received.equals("Exit")) 
                {  
                    System.out.println("Client " + this.s + " sends exit..."); 
                    System.out.println("Closing this connection."); 
                    this.s.close(); 
                    System.out.println("Connection closed"); 
                    break; 
                } 
                num=Integer.parseInt(received);
                try{
                 if (num<0) {
     throw new NegativeNumberException(received);
     }
                 }catch(Exception e) {
                 toreturn=e.toString();
                 dos.writeUTF(toreturn);
                 System.out.println("Closing this connection."); 
                        this.s.close(); 
                                       }
                count=1;
                for(int i=1;i<=num;i++) {
                 count=count*i;
                 System.out.println(+count);
                }
                toreturn = "Factorial of "+num+"="+count; 
                dos.writeUTF(toreturn);  
                Thread.sleep(1000);
                // write on output stream based on the 
                // answer from the client 
                } catch (IOException e) { 
                e.printStackTrace(); 
            } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}  
        }     
        try
        { 
            // closing resources 
            this.dis.close(); 
            this.dos.close(); 
              
        }catch(IOException e){ 
            e.printStackTrace(); 
        }  
        }
    }










Client Side
  
import java.io.*; 
import java.net.*; 
import java.util.Scanner; 
  
// Client class

public class factclient  

    public static void main(String[] args) throws IOException  
    { 
        try
        { 
            Scanner scn = new Scanner(System.in); 
              
            // getting localhost ip 
            InetAddress ip = InetAddress.getByName("localhost"); 
      
            // establish the connection with server port 5056 
            Socket s = new Socket(ip, 5060); 
      
            // obtaining input and out streams 
        DataInputStream dis = new DataInputStream(s.getInputStream()); 
        DataOutputStream dos = new DataOutputStream(s.getOutputStream()); 
      
            while (true)  
            { 
                System.out.println(dis.readUTF()); 
                String tosend = scn.nextLine(); 
                dos.writeUTF(tosend); 
                  
                // If client sends exit,close this connection  
                // and then break from the while loop 
                if(tosend.equals("Exit")) 
                { 
                    System.out.println("Closing this connection : " + s); 
                    s.close(); 
                    System.out.println("Connection closed"); 
                    break; 
                } 
                  
                // printing date or time as requested by client 
                String received = dis.readUTF(); 
                System.out.println(received);
                if(received.equals("NegativeNumberException: Operation Factorial is Denied by server")) {
                 s.close(); 
                    System.out.println("Connection closed Due to Exception");
                    break;
                    
                }
            } 
              
            // closing resources 
            scn.close(); 
            dis.close(); 
            dos.close(); 
        }catch(Exception e){ 
            e.printStackTrace(); 
        } 
    } 


Credits: Sahil

/* Note The Point: In Above Solution Server Continues Run In Background Even After Producing  User Define Exception.
 IF u want to discontinue Just Add System.exit(0) In the Exception Catch Block*/

0 comments:

Post a Comment