1

Currently in our application , we use java nio blocking socket channel for writing data out.

           socketChannel = SocketChannel.open();
            socketChannel.setOption(StandardSocketOptions.SO_KEEPALIVE, config.getConnectionKeepAlive());
            socketChannel.configureBlocking(true);


    protected void trySendEvent(final Object inputEvent) {
        final byte[] eventAsBytes = (byte[]) inputEvent;
        final ByteBuffer buffer = ByteBuffer.allocate(eventAsBytes.length);
        buffer.put(eventAsBytes);
        buffer.flip();
        int bytesWritten;
        try {
            bytesWritten = writeEvent(buffer , eventAsBytes);
        } catch (final IOException e) {
            log.error("No connection with client.");
            reconnect();
            try {
                bytesWritten = writeEvent(buffer , eventAsBytes);
            } catch (final IOException ex) {
                log.error("Failed to send event to client.");
            }
        }
    }

When the connection from peer client is reset , our application relies on the IO exception to identify a closed connection and reconnect .

Although the connection is closed , IO exception is not thrown until the local TCP buffer is filled meaning first few writes will be in buffer and never throw an exception. So first few writes are lost and never sent to client

So my question is . Is there any reliable way to check the state of the socket ??

"As per the java documentation socketChannel.isConnected() returns true if socket was connected before not the current state"

Any help is appreciated !

eprabab
  • 101
  • 6

0 Answers0