How to time out a read from socket

E

Ed

Guys,

I have a piece of code that is reading from a socket until it receives
characters that indicate that it is end of the string. This is for a
telnet application and as people may know - a telnet response can come
back as one or many message.

Anyhow the problem is more generic than telnet so I don't want this to
confuse people.

The code block I have is as follows (message is a StringBuffer, reader
is a BufferedReader):

if (endOfResponseString != null)
{
//Read the response from the server
c = 0;

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

The problem is that when the server errors it never returns the
endOfResponseString I am looking for. The communication can take
seconds to finish but I would ideally like the reader.read or this
whole block to timeout after say 10 seconds.

Is there a simple way to do this? I do want the program to block for
the 10 seconds but after that time to break out.

Many thanks for any suggestions

Ed
 
J

John Davison

Ed said:

-- snippy --
Is there a simple way to do this? I do want the program to block for
the 10 seconds but after that time to break out.

java.lang.Socket.setSoTimeout(int timeout) (see the docs)

John Davison
Compass Engineering Group
 
A

Alan Meyer

Ed said:
Guys,

I have a piece of code that is reading from a socket until it receives
characters that indicate that it is end of the string. This is for a
telnet application and as people may know - a telnet response can come
back as one or many message.
....

Ed,

I don't know how far you've gotten in your application,
or how much research you've done on Telnet. I presume
you know this, but just in case you don't, the telnet protocol
supports "out-of-band" data that your application will
have to handle. The OOB data consists of one or
more characters prefixed by a hex FF character, and is
intended for communication between the telnet protocol
handlers at each end, beneath the level of the application.

It can get a bit complicated.

See the telnet RFC for details.

Alan
 

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

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top