How to close a port after using server sockets

In my application, I create an instance of ServerSocket with some port. After I'm done, I close the socket, but when I try to create a new ServerSocket on the same port, it throws:

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

If I create a 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()); } } 
+4
source share
4 answers

Have you tried calling setReuseAddress(true) on the server socket? It is normal for a TCP state machine to enter the TIME_WAIT state. See here for a detailed explanation.

+2
source

This is because on some OS If you wait a bit (for example, a couple of minutes), then you can again access the port.

It is not recommended to open and close servers on the port. It is better to open it and keep it open as necessary. Then close it when done. Do not open / close / open / close / open / close ...

0
source

Just close the socket when done. It automatically disables the port that it is listening on. Never open the socket (port) when you are done.

0
source

This means that the server is already open, you need to check the user input or client input, which says to close the server, for example

 while( bufferedinputstream != "quit" ) try{ ... } 

As soon as your server opens, it just opens until something closes it.

-2
source

All Articles