Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to close port after using server sockets [closed]

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());
        }
}
like image 527
dan Avatar asked May 27 '11 03:05

dan


People also ask

What happens when server socket closed?

Closing a ServerSocket will prevent new connections from being created, but it won't shut down existing connections. ServerSocket is the listening socket involved only in creating a connection. The data communication is handled distinctly in the Socket returned by ServerSocket.

How do I close a port in socket programming?

close() call shuts down the socket associated with the socket descriptor socket, and frees resources allocated to the socket. If socket refers to an open TCP connection, the connection is closed. If a stream socket is closed when there is input data queued, the TCP connection is reset rather than being cleanly closed.

How do I close a server socket?

The close() method of ServerSocket class is used to close this socket. Any thread currently blocked in accept() will throw a SocketException.

What can happen if you do not close a socket when you finish using it?

One way or another, if you don't close a socket, your program will leak a file descriptor. Programs can usually only open a limited number of file descriptors, so if this happens a lot, it may turn into a problem.


2 Answers

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.

like image 107
Code Painters Avatar answered Sep 21 '22 05:09

Code Painters


It is because there is a cooldown period implemented on some O.S. If you wait a little (a couple of minutes for example), then you should be able to access the port again.

That being said, it is not a good idea to open and close serversockets on a port. It is better to open it and keep it open as long as necessary. Then close it when you are done. Don't open/close/open/close/open/close...

like image 42
Jérôme Verstrynge Avatar answered Sep 18 '22 05:09

Jérôme Verstrynge