1
\$\begingroup\$

Is it a good practice to initialize the BufferedReader and DataOutputStream in infinite loop?

        ServerSocket welcomeSocket = new ServerSocket(8080);
        Socket connectionSocket = welcomeSocket.accept();

        while (true) {
            BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); //close it
            DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); //close it
            //... Do read/write stuff
        }

Connection establishes successfully and communication happens normally. Just want to know that whether it is a good practice or not? It is a Java code.

Thanks.

\$\endgroup\$
3
\$\begingroup\$

At the very least use a try-with-resources:

while (true) {
    try(BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())),
            DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream())){
        //... Do read/write stuff
    }
}

Then when the loop body is done (by normal control flow or by exception) the streams will be closed normally.

However if you want a lot of clients connecting at a time and you want them all to be able to interact at the same time you will need to delve into the async IO in the java.nio.channels package.

\$\endgroup\$
  • \$\begingroup\$ Hmm, that's better option. It means the approach I mentioned is a poor one. \$\endgroup\$ – Faizan Mubasher May 2 at 15:11
0
\$\begingroup\$

It seems that this class is responsible for managing control flow (the loop) and establishing connections (the streams) so it breaks the single responsibility principle.

But in the end, theoretically, it doesn't matter if the stream initialization is inside this loop or in another class called from this loop. If the requirements say streams have to be opened in a loop, then they have to be.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.