Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing over a disconnected socket does not throw

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.

like image 206
kellogs Avatar asked Aug 09 '11 00:08

kellogs


1 Answers

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.

like image 177
user207421 Avatar answered Sep 22 '22 23:09

user207421