开发者

Java: InputStream.read doesn't wait for input?

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 waitin开发者_StackOverflowg for input but returns -1. Is there any reason why inputstream.read(Line) wouldn't wait for input as it's meant to?


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...)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜