0

G'day, I'm working on a proxy, but one of the socket's inputstream is being weird:

while(true) {
        try {
            while ((BytesRead = inputstream.read(Line)) != -1) {
                OtherSocket.Write(Line, BytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

I have pretty much the same thing for the OtherSocket, but on this one, it keeps repeating as if the server keeps sending data, I'm guessing that inputstream.read(Line) isn't waiting for input but returns -1. Is there any reason why inputstream.read(Line) wouldn't wait for input as it's meant to?

2
  • Is this really Java? Is OtherSocket a custom class? Commented Oct 11, 2011 at 11:37
  • If this code is Java it uses an unidiomatic writing style, which makes it hard to understand the code. Commented Oct 11, 2011 at 11:40

1 Answer 1

2

I believe InputStream.read will keep returning -1 after the socket has been closed by the other end.

Why would you want to keep trying to read from a stream which has already returned -1 from read? That seems to be the bug to me. If you want to keep the while(true) loop you should put a break; statement after the inner while loop, so that if you've just managed to reach the end of the stream normally with no problems, you can just exit the outer loop.

I strongly suspect that trying to read from a stream after it's already failed is a bad idea too, by the way.

(I'd also suggest that you start following more conventional Java naming - it's very odd to see PascalCase variable names. It's also odd to see a method called Write - that's certainly not something on java.io.OutputStream...)

Sign up to request clarification or add additional context in comments.

1 Comment

In regards to Jon's answer, you're not showing us which implementation of InputStream you're using. Each one gets to define EOF conditions. We need to know the concrete implementation to be of more help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.