blacblu
blacblu

Reputation: 297

Client application socket closed after printing string

I'm building a Java client application which needs to send a message to a server and receive a response afterwards. I can send the message successfully, the problem is that I can't get the response because I get an IO exception ("Socked is closed") when trying to read the 'BufferedReader'.

This is my code, so far:

public class MyClass {

    /**
     * @param args the command line arguments
     */
    @SuppressWarnings("empty-statement")
    public static void main(String[] args) {
        JSONObject j = new JSONObject();
        try {
            j.put("comando", 1);
            j.put("versao", 1);
            j.put("senha", "c4ca4238a0b923820dcc509a6f75849b");
            j.put("usuario", "1");
            j.put("deviceId", "1");

        } catch (JSONException ex) {
            System.out.println("JSON Exception reached");
        }

        String LoginString = "{comando':1,'versao':1,'senha':'c4ca4238a0b923820dcc509a6f75849b','usuario':'1','deviceId':'1'}";
        try {
            BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));

            Socket clientSocket = new Socket("10.1.1.12", 3333);
            System.out.println("Connected to the server successfully");
            PrintWriter outToServer = new PrintWriter(clientSocket.getOutputStream(),true);

            outToServer.println(j.toString());
            outToServer.close();
            System.out.println("TO SERVER: " + j.toString());

            BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

            String resposta = inFromServer.readLine();
            System.out.println("FROM SERVER: " + resposta);

            clientSocket.close();
        } catch (UnknownHostException ex) {
            System.out.println("Could not connect to the server [Unknown exception]");
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        } 
    }
}

I know that the socket is being closed because of the OutToServer.close() but closing the stream is the only way to send the message. How should I approach this situation?

Upvotes: 0

Views: 1265

Answers (2)

Jin Kwon
Jin Kwon

Reputation: 21978

flush() is not the case when it comes with new PrintWriter(, true).

The real problem is that you are closing the PrintWriter outToServer which wraps the underlying InputStream, again, came from the Socket.

When you close the outToServer you're closing the whole socket.

You have to use Socket#shutdownOutput().

You don't even have to close the output if you want to keep the socket's in/out channels for further communications.

  1. flush() when you are done with any writeXXX. Those writeXXX practically don't mean you sent those bytes and characters to other side of the socket.

  2. You may have to close the output, and output only, to signal the server that you sent all you had to send. This is really a matter of the server-side socket's desire.

final Socket socket = new Socket(...);
try {
    final PrintStream out = new PrintStream(socket.getOutputStream());
    // write here
    out.flush(); // this is important.
    socket.shutdownOutput(); // half closing

    // socket is still alive

    // read input here

} finally {
    socket.close();
}

Upvotes: 2

gaborsch
gaborsch

Reputation: 15758

Try to call outToServer.flush()

That will try to flush the data from the buffer, although it still not guarantees that it will be sent.

Upvotes: 1

Related Questions