0

I have the code below When I do not have the close ServerSocket statement I get an error saying it is a resource leak but when I add the close statement Eclipse tells me the code is unreachable, How can I change the code to close the socket outside of the while statement?

serverSocket = new ServerSocket(ServerPort);
    File incomingFile = new File("testfile.txt");

    while (true) {
        System.out.println("Waiting For File");
        Socket incomingSocket = serverSocket.accept();
        byte[] mybytearray = new byte[(int) incomingFile.length()];
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(incomingFile));
        bis.read(mybytearray, 0, mybytearray.length);
        bis.close();
        OutputStream os = incomingSocket.getOutputStream();
        os.write(mybytearray, 0, mybytearray.length);
        os.flush();
        if (incomingSocket != null) {
            incomingSocket.close();
        }

    }
    if(serverSocket != null) {
        serverSocket.close();
    }
user3389199
  • 5
  • 1
  • 4

1 Answers1

3

The proper way to prevent resource leaks is using try..finally

    serverSocket = new ServerSocket(serverPort);
    try {
        File incomingFile = new File("testfile.txt");
        while (true) {
            // your code
        }
    } finally {
        serverSocket.close();
    }

or using the try-with-resources construct like this

    try (serverSocket = new ServerSocket(serverPort)) {
        File incomingFile = new File("testfile.txt");
        while (true) {
            // your code
        }
    }

The reason that code is unreachable is because your while loop is unterminated. Note also that serverSocket cannot be null at that point in the code because constructors must always result in a new instance unless an exception is thrown.

gknicker
  • 5,509
  • 2
  • 25
  • 41