How to check if a server has disconnected a socket

Discussion in 'Java' started by Jarle Jacobsen, Aug 31, 2004.

  1. Hi.

    Can anybody help me with the following?

    I'm using to connect to a server. The socket is part of a
    client application, and I connect to the server at startup. The application
    should be able to handle a lost connection due to a restart of the server or
    any other reason. Is it a way to check if the socket connection is still
    connected or if the connection has been reset?

    Jarle Jacobsen, Aug 31, 2004
    1. Advertisements

  2. Yes.

    If reading from or writing to the streams associated with the Socket
    indicates EOF, the connection has been broken and you can (attempt to)

    Or, if you are using a java.nio.channels.Selector, the channel will
    become ready for reading or writing when the connection breaks. Note
    that you still need to actually read or write to determine whether EOF
    has been reached.

    Gordon Beaton, Aug 31, 2004
    1. Advertisements

  3. Hi,
    The only way to know if the connection is alive is to write on the
    socket. However depending on your protocol sometimes you're not able to
    write on the socket to check the connection (for example if you are waiting
    for a response, you will never be aware of this connection loose), this is
    why you can set the KEEP_ALIVE option that will check the connection every 2
    hours. From my experience, the methods "boolean isBound()" and "boolean
    isConnected()" does not give an accurate information if you have connected
    the socket once (it seems to be normal since with tcp you can't be aware of
    a connection loose unless you are in the two case I was speaking about
    This thread discuss of this issue:
    Hope this will help,

    MERIGON Olivier, Aug 31, 2004
  4. Thanks!
    The postings in that thread explained a lot.

    Jarle Jacobsen, Aug 31, 2004
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.