0

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.

HimaaS
  • 413
  • 3
  • 6
  • 13

2 Answers2

0

Use try-with-resources Statement something like:

            try (ObjectOutputStream out =
                           new ObjectOutputStream(socket.getOutputStream()) {
               .....
            }
Har Krishan
  • 273
  • 1
  • 11
  • go thru below link to see how to use try with resource statement https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html – Har Krishan Dec 04 '17 at 08:03
0

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();
    }
Har Krishan
  • 273
  • 1
  • 11