Search code examples
javasocketsserversocket

I'm not able to send response back to the client


I'm creating a server and a client. Right now I am able to send a message from the Client to the ServerThread, and the ServerThread is able to get the message. But when the ServerThread tries to respond back, the Client doesn't get the response, but the message was sent. It seems like it's waiting for the response, but is never able to receive it.

ServerThread:

public class ServerThread extends Thread {
   private Socket socket;
   private DataOutputStream outToClient;
   private BufferedReader inFromClient;

   public ServerThread(Socket socket) {
      try {
         System.out.println("Thread started");
         this.socket = socket;
         outToClient = new DataOutputStream(socket.getOutputStream());
         inFromClient = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      } catch (FileNotFoundException e) {
         e.printStackTrace();
      } catch (Exception e) {
         e.printStackTrace();
      }
   }

   public void run() {
      System.out.println("Thread running");
      try {
         System.out.println("ServerThread: " + inFromClient.readLine());
         outToClient.writeBytes("I Can help you");
      } catch (Exception e) {
         e.printStackTrace();
      }
   }
}

Server:

public class Server {
   public static final int PORT = 5589;

   public static void main(String[] args) {
      ServerSocket socket;

      try {
         socket = new ServerSocket(5589);

         while (true)
            new ServerThread(socket.accept()).start();
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

Client:

public class Client {
   public static void main(String args[]) throws Exception {
      Socket socket = new Socket("localhost", App.PORT);
      BufferedReader inFromServer = new BufferedReader(new InputStreamReader(socket.getInputStream()));
      PrintWriter outToServer = new PrintWriter(socket.getOutputStream(), true);

      outToServer.println("Hello, I'm Lost");

      System.out.println(inFromServer.readLine()); //Hangs on this line

      socket.close();
   }
}

Solution

  • Your data is buffered on the server side and not sent automatically until the buffer is full: you should .flush() on the server side after you .writeBytes() to ensure that it gets sent, even if you don't reach the buffer size (which is dependent on both the OS and the socket configuration).