How to close port after using server sockets

dan picture dan · May 27, 2011 · Viewed 15.9k times · Source

In my application I create a ServerSocket instance with some port. After I am finished, I close the socket, but when I try to make a new ServerSocket on the same port, it throws:

"java.net.BindException: Address already in use"

If I create the ServerSocket with a different port, then it works.

ServerSocket.isClosed also returns true

What is the problem?

public void run() {
    try {
        BufferedInputStream bufferedinputstream = new BufferedInputStream(
                                                        new FileInputStream(fileReq));
        BufferedOutputStream outStream = new BufferedOutputStream(
                                                        cs.getOutputStream());
        byte buffer[] = new byte[1024];

        int read;
        System.out.println(cs);
        while ((read = bufferedinputstream.read(buffer)) != -1)
        {
            outStream.write(buffer, 0, read);
            outStream.flush();
        }
        System.out.println("File transfered");
        outStream.close();
        bufferedinputstream.close();

        try {
            this.finalize();
        } catch (Throwable e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
    }
} catch (Exception e) {
    System.out.println("Exce....");
    System.out.println(e.getMessage());
}
finally
{
    if ( cs != null)
        try {
            int usedPort=cs.getLocalPort();
            System.out.println("Closing "+cs);
            cs.close();
            System.out.println(cs+" Closed");
            System.out.println("asd"+cs.isClosed());
            portManager.getInstance().mp.put(usedPort,true);
        } catch (IOException e) {
            System.err.println("in sendToClient can't close sockt");
            System.err.println(e.getMessage());
        }
}

Answer

Code Painters picture Code Painters · May 27, 2011

Have you tried calling setReuseAddress(true) on the server socket? It's normal for the TCP state machine to enter TIME_WAIT state. For detailed explanation look here.