How to time out a read from socket

Discussion in 'Java' started by Ed, Oct 12, 2004.

  1. Ed

    Ed Guest

    Guys,

    I am looking to read from a socket and keep reading until I receive a
    certain set of characters. However in an "error" situation these
    characters never arrive, the socket "dries up" and I need to be able
    to spot this.

    I have a loop as follows:


    while((c = m_reader.read()) != -1)
    {
    message.append((char)c);
    if (message.toString().endsWith(endOfResponseString))
    {
    break;
    }
    }

    Obviously if the server misbehaves, the m_reader.read() blocks and
    everything hangs.

    What I want is some way of "timing out" the loop after a period of
    inactivity.

    The server is a remote IP server so a message can be sent in separate
    "chunks". m_reader is a BufferedReader but that can be changed if it
    helps achieve the desired affect.

    Any ideas?

    Cheers

    Ed
     
    Ed, Oct 12, 2004
    #1
    1. Advertising

  2. On 12 Oct 2004 05:08:19 -0700, Ed wrote:
    > I have a loop as follows:
    >
    > while((c = m_reader.read()) != -1)
    > {
    > message.append((char)c);
    > if (message.toString().endsWith(endOfResponseString))
    > {
    > break;
    > }
    > }
    >
    > Obviously if the server misbehaves, the m_reader.read() blocks and
    > everything hangs.
    >
    > What I want is some way of "timing out" the loop after a period of
    > inactivity.


    It looks to me like the remote process isn't closing his end of the
    connection as maybe it should when an error occurs, or you'd get EOF
    here.

    Anyway you can use Socket.setSoTimeout() to limit the time you block
    while reading. Or use java.nio.Selector.select() with a timeout,
    *before* reading from the corresponding SocketChannel.

    /gordon


    --
    [ do not email me copies of your followups ]
    g o r d o n + n e w s @ b a l d e r 1 3 . s e
     
    Gordon Beaton, Oct 12, 2004
    #2
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ed
    Replies:
    2
    Views:
    488
    Alan Meyer
    Oct 1, 2004
  2. Laszlo Nagy
    Replies:
    1
    Views:
    4,855
    Mark Wooding
    Jan 27, 2009
  3. Jean-Paul Calderone
    Replies:
    0
    Views:
    971
    Jean-Paul Calderone
    Jan 27, 2009
  4. Laszlo Nagy
    Replies:
    0
    Views:
    552
    Laszlo Nagy
    Feb 1, 2009
  5. Steve Holden
    Replies:
    0
    Views:
    666
    Steve Holden
    Feb 1, 2009
Loading...

Share This Page