title: Basic server and Client interaction- Java
body: <p>Good day,</p>
  
  <p>The code below runs but the server only writes the string after i terminate it or the client only receives the string i sent after i terminate the running server.
  What should happen is upon connection the client sends a hello message to the server which the server reads and outputs to the console then server writes a message back to client then client reads the message and outputs it to console before disconnecting promptly.</p>
  
  <pre><code>    public class Server 
      {
      public static void main(String[] args) 
      {
      ServerSocket ss;
      try {
      ss=new ServerSocket(2018);
      Socket s=ss.accept();
      System.out.println("connected...");
      Handler h =new Handler(s);
      Thread t=new Thread(h);
      t.start();
      }catch(IOException ex)
      {
      ex.printStackTrace();
      }
  
  //client handler.
  
      public Handler(Socket s) 
          {
              cs=s;
          }
  
          @Override
          public void run() 
          {
  
              try 
              {
              pw=new PrintWriter(cs.getOutputStream());
              sc=new Scanner(cs.getInputStream());
              pw.write("SERVER SAYS:Hello");
              pw.flush();
              System.out.println(sc.nextLine());
  
              }catch(IOException e)
              {
                  e.printStackTrace();
              }
          //then the client.
  
           public class Client {
          public static void main(String[] args) 
          {
              Socket s;
              PrintWriter pw;
              Scanner sc;
  
              try {
              s=new Socket("localhost",2018);
              pw=new PrintWriter(s.getOutputStream());
              sc=new Scanner(s.getInputStream());
              pw.write("HELLO");
              pw.flush();
              String msg=sc.nextLine();
              System.out.println(msg);
              }catch(IOException e)
              {
              e.printStackTrace();
              }
  </code></pre>