title: simple client - server talking to each other classes in Java
body: <p>I am trying to figure out why I can send messages to the client from the server but when I try the other way around (to send messages from the client to the server) the program halts like it is waiting for some action to happen.</p>
  
  <p>also how to prevent the sockets from being closed immediately.</p>
  
  <p>this is the code:</p>
  
  <p><strong>Client Class</strong>   </p>
  
  <pre><code>import java.io.*;
  import java.net.*;
  
   public class Client {
  
  public static void main(String[] args) {
  
      Client aClient = new Client();
  
  
          aClient.run();
  
  
  }
  
  private Socket socket;
  private PrintWriter toServer;
  private BufferedReader fromServer;
  
  public void run() {
  
      try {
          socket = new Socket("localhost", 9000);
          if (socket.isConnected()){
              System.out.println("CONNECTED");
          }
  
          fromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
          toServer = new PrintWriter(socket.getOutputStream());
  
  
  
  
          toServer.print("hello server");
  
  
  
          System.out.print(fromServer.readLine());
  
          toServer.close();
         socket.close();
  
      } catch (Exception error) {
          System.out.println("CLIENT ERROR: " + error);
  
      }
  }
  }
  </code></pre>
  
  <p><strong>Server Class</strong></p>
  
  <pre><code>import java.io.*;
  import java.net*;
  
  
  public class Server {
  
  public static void main(String[] args) {
  
      Server aServer = new Server();
      aServer.run();
  
  }
  
  private ServerSocket mainSocket;
  private Socket socket;
  private PrintWriter toClient;
  private BufferedReader fromClient;
  
  public Server(){
    try{
        mainSocket = new ServerSocket(9000);
  
  }
    catch (Exception error){
        System.out.print("Error :"+error);
    }
  }
  public void run() {
       System.out.println("WAITING FOR CLIENTS");
      try {
  
          socket = mainSocket.accept();
  
               if(socket.isConnected()) {
                   System.out.println("CONNECTED.");
               }
  
  
          fromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
          toClient = new PrintWriter(socket.getOutputStream());
  
  
          System.out.println(fromClient.readLine());
          toClient.print("hello Client");
          toClient.close();
  
          }
       catch (Exception error) {
          System.out.println("SERVER ERROR :" + error);
      }
  
  
  }
  
  
  }
  </code></pre>