java - InputStream of socket not closing on peer loss -
i connecting device opening socket.
incoming data perform read
action on inputstream
in different thread.
when take away electricity of peer device connected to, inputstream doesn't recognize loss of connection.
this code wait input:
stringbuilder sb = new stringbuilder(); string result = ""; int c; try { log.info( "waiting data..." ); while ( ( ( c = inputstream.read() ) >= 0 ) ) { if ( c == -1 ) { log.info( "is -1" ); } /* * todo: <lf> can't delimiter define end of message. should * parameterized. */ if ( c == 0x0a /* <lf> */ ) { result = sb.tostring(); sb.delete( 0, sb.length() ); } else if ( c != 0x0d /* <cr> */ ) { sb.append( (char) c ); } if ( !result.isempty() ) { log.info( getname() + ": received message: " + result ); listener.messagereceived( result.getbytes() ); result = ""; } } log.info( "stream ended" ); disconnect(); listener.closed(); } catch ( ioexception | resourceexception e ) { try { log.info( "in catch block" ); disconnect(); listener.closed(); throw new resourceexception( "an error occured during receiving of message device, or connection timed out.", e ); } catch ( resourceexception e1 ) { e1.printstacktrace(); } }
this inside of jca connector if information use in case. knowledge inputstream receives -1
when stream interrupted , should jump stream ended
log doesn't happen.
why doesn't recognize connection can't available, since remote peer powered off?
a 'read timeout', suggested @kayaman, usual method of implementing heartbeat. need 'timingout' boolean, initialized false. whenever data received, data or heartbeat poll reply, set false. upon read timeout check 'timingout' flag. if false, send poll request , set 'timingout' true. if true, close socket , take 'connection lost' action/s.
no need separate thread. no wasteful polling if data being transferred often.
Comments
Post a Comment