Question

the writer:

   socket.setSendBufferSize(1);
   socket.setTcpNoDelay(true);
   writer = new BufferedWriter(
          new OutputStreamWriter(socket.getOutputStream(), "UTF-8"));

is used as follows:

try {
        writer.write(packet.toXML());
        writer.flush();
        ...
    }
    catch (Exception ioe){
        if (!done) {
            done = true;
            ... 
        }       
    }

This is client side code. When its server disconnects the socket (also java code), how come the client will only throw after 5 - 10 minutes ? Should it not throw at the first attempt to write over the dead connection ?

Thanks

Edit:

after shutting down the server, here are the TCP states:

tcp        0      0 server:443     client:50283   FIN_WAIT2 

tcp4       0      0  cient.50283     server.443       CLOSE_WAIT

Edit2:

client is an android application. Ran from phone, the second packet written causes a throw. Ran from an emulator (Mac underneath) the fourth write() will throw.

Was it helpful?

Solution

Should it not throw at the first attempt to write over the dead connection ?

No. All it knows is that a FIN has been received, which could have just been a shutdownOutput() by the peer - it could still be reading. So TCP has to send the data. If the peer has closed, it will issue an RST, which TCP will provide to the application on a subsequent write.

OTHER TIPS

According to docs, readers should return -1 on read() operations, but I was not getting anything because some XmlPullparser was getting in the way

parser.setInput(connection.reader);

So, the writer behaves as EJP described above, but if you have access to source code then we could instantiate our connection.reader as some InputStreamReaderEx like so:

/** * @author kellogs * */ public class InputStreamReaderEx extends InputStreamReader {

/* (non-Javadoc)
 * @see java.io.BufferedReader#read()
 */
@Override
public int read() throws IOException {
    // TODO Auto-generated method stub
    int ret = super.read();

    if (ret == -1)
    {
        int l = 4;
    }

    return ret;
}

/* (non-Javadoc)
 * @see java.io.BufferedReader#read(char[], int, int)
 */
@Override
public int read(char[] buffer, int offset, int length) throws IOException {
    // TODO Auto-generated method stub
    int ret = super.read(buffer, offset, length);

    if (ret == -1)
    {
        int l = 4;
    }

    return ret;
}

}

and get notified when the other peer goes away

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top