0

I did a script to exchange data between a client and a server with socket on specific port. In order, I am expecting:

  • Server is listening

  • Client opens a socket

  • Server akwnoledges by sending a int -> never received !

I just noticed that my client receives the int, when I quit the server brutally

Here is my (simple) code. Client:

Socket socket = new Socket(SERVER_ADDR, PORT);
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream());
DataInputStream dIn = new DataInputStream(socket.getInputStream());

Log.v("[DEBUG]", "waiting aknowledgement");
status = dIn.readInt();  //<-- BLOCKS HERE
Log.v("[DEBUG]", "ack"); //<-- RECEIVED WHEN SERVER IS EXITED

Server:

try {

    DataInputStream stdIn = new DataInputStream(client.getInputStream());
    DataOutputStream stdOut = new DataOutputStream(client.getOutputStream());

    while (incoming) {

        stdOut.writeInt(1);
        stdOut.flush();

        System.out.println("Waiting...");  
        var_from_client = stdIn.readInt(); //<-- BLOCKS HERE (BECAUSE CLIENT IS BLOCKED)

        // ...
    }
} catch (Exception e) {}

How to explain this error?

Anduriel
  • 93
  • 2
  • 10

1 Answers1

0

'Socket not flushing data' has exactly nothing to do with it. This is a deadlock, caused by a bug in your application.

  1. Your server sends an int.
  2. Your client receives the int.
  3. Your server blocks trying to read another int.
  4. Your client doesn't send an int.
  5. The server can never send another int because it is blocked waiting for the non-existent reply int.
  6. Your client blocks while trying to receive another int because the server is blocked from sending it.

Solution: send the int from the client.

Notes:

  1. Flushing the output stream of a socket does nothing, and neither does flushing a DataOutputStream wrapped directly around it.
  2. NEVER ignore exceptions.
user207421
  • 305,947
  • 44
  • 307
  • 483
  • Please see http://stackoverflow.com/questions/41685367/send-data-from-android-mobile-to-java-server?noredirect=1#comment70569691_41685367. I didn't ignored exception, and I sent correctly my data. Regards – Anduriel Jan 17 '17 at 06:57