Reputation: 5
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?
Upvotes: 0
Views: 2054
Reputation: 1503459
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
...)
Upvotes: 2