Best way to close the socket and streams

107 views Asked by At

In eclipse in one of the classes SonarLint and sonarqube server saying socket is not closed, even I closed it.

FYR: enter image description here

What is the best way to close the socket? Could anyone please guide me.

Note: I don't get this error if I don't have out = new ObjectOutputStream(...) code in the same try block.

2

There are 2 answers

1
Har Krishan On

Use try-with-resources Statement something like:

            try (ObjectOutputStream out =
                           new ObjectOutputStream(socket.getOutputStream()) {
               .....
            }
0
Har Krishan On

Here is working code:

    try (Socket socket=new Socket(ipAddress, port);
            ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream())) {
           //this is how you can use socket & out
        out.write(null);
        socket.getInetAddress();
    }