Closing a socket when trying with resources

I am trying to write simple socket code that has the following basic form:

try(BufferedReader request = new BufferedReader(new InputStreamReader(sock.getInputStream()))){ //Do some work... } //BufferedReader gets closed, but also makes the socket close ... ... response.write(blah);//Causes exception because socket is closed 

My problem is that the socket is closing, but I don't think it should be. The try-with resource creates a BufferedReader and then automatically closes it when I leave the try block, but for some reason it also closes the entire socket! Therefore, when I get a response code that later uses the same socket, I get an exception. Is there any way to fix this? Or do I just not need to use try-with-resources (which would be less than ideal)?

+4
source share
2 answers

BufferedReader.close () closes the supporting stream.

The workaround is a wrapper thread that does not propagate the close () function

+6
source

Code:

 new BufferedReader( new InputStreamReader( sock.getInputStream())) 

transferring a socket stream to a reader wrapped in a BufferedReader, but this is the only and only stream.

+1
source

Source: https://habr.com/ru/post/1440646/


All Articles