How to time out a read from socket

E

Ed

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
 
G

Gordon Beaton

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
 

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. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top