Advanced Java (2160707)

BE | Semester-4   Winter-2018 | 20-11-2018

Q2) (c)

Write a client-server application using TCP Sockets where client can send message and server respond with the reverse of them.

Client.java

import java.io.*;
import java.net.*;

public class Client extends Thread
{
  Message;
 ServerSocket sock;
 Client(int port) throws Exception
  {
    sock=new ServerSocket(port);
  }

 public void run()
 {
  try
  {
    Socket so=sock.accept();
    while(true)
    {
      DataInputStream inp=new DataInputStream(System.in);
      DataInputStream inn=new DataInputStream(so.getInputStream());
      DataOutputStream out=new DataOutputStream(so.getOutputStream());
      //System.out.println(inn.readUTF());
      Message=inn.readUTF();
      char []jp=new char[100];
      char []jp2=new char[100];
      int j=0;
      jp=Message.toCharArray();
      for(int i=jp.length-1;i>=0;i--)
      {
        jp2[j]=jp[i];
        j++;
      }
      String rev=new String(jp2);
      out.writeUTF(rev);
    }
  }
  catch(Exception eee){}
 }
  public static void main(String[] args) throws Exception
  {
    Thread t=new Client(Integer.parseInt(args[0]));
    t.start();
  }
}

Server.java

import java.io.*;
import java.net.*;

public class Server
{
 public static void main(String[] args) throws Exception
 {
  String Message;
  Socket so=new Socket("localhost",Integer.parseInt(args[0]));
  try{while(true)
   {
   DataInputStream inp=new DataInputStream(System.in);
   DataInputStream inn=new DataInputStream(so.getInputStream());
   DataOutputStream out=new DataOutputStream(so.getOutputStream());
   Message=inp.readLine();
   out.writeUTF(Message);
   System.out.println(inn.readUTF());
   }
  }
  catch(Exception eee){}
 }
}