Two way interaction of client server in java

// here from both ends the message will be sent and read


//client code

public class TwoWayInteractionClient {

   
    public static void main(String[] args) throws IOException {
       
        Socket obj = new Socket("localhost",8844);
        DataOutputStream dout = new DataOutputStream(obj.getOutputStream());
        dout.writeUTF("This message is from client side");
        dout.flush();
       
       
        //ServerSocket rec = new ServerSocket(8134);
        DataInputStream din = new DataInputStream(obj.getInputStream());
        String newdata = (String)din.readUTF();
        System.out.println(" the new msg is " +newdata);
       
    }
   
   
}

output
the new msg is This msg is send from server


//server code

public class TwoWayInteractionServer {
     public static void main(String[] args) throws IOException {
       
    ServerSocket obj1 = new ServerSocket(8844);
        Socket obj = obj1.accept();
        DataInputStream din = new DataInputStream(obj.getInputStream());
        String str = (String)din.readUTF();
        System.out.println("The message from client is  " +str);
       
       // while two way interaction no need to create new port
        DataOutputStream dout =  new DataOutputStream(obj.getOutputStream());
        dout.writeUTF("This msg is send from server");
        dout.flush();
     }
   
   
}

output
The message from client is  This message is from client side











No comments:

Post a Comment