0

I'm writing socket programs in Java and sometimes get this error. I have some questions:

1) I use Eclipse to run my socket apps and click "terminate" at last but sometimes still get that error. Why?

2) Is there any way to close port programmatically? Something like this:

if(isPortOpen(portNumber)) {
   closePort(portNumber);
}
//// Run my app here

3) Is there any way to avoid this error (in programming or OS)?

emeraldhieu
  • 9,380
  • 19
  • 81
  • 139

2 Answers2

2

The socket option SO_REUSEADDR can help to re-use a port that has previously been in use (a program terminated seconds ago).

Simply create an unconnected socket, use

socket.setReuseAddress(true);

before connecting the socket and then connect it.

See the javadoc and this SO post

Community
  • 1
  • 1
BertNase
  • 2,374
  • 20
  • 24
1
  1. Ideally when the application is killed, the open ports should be closed.
  2. If you have the socket object for that port, then socket.close() should close the port.
  3. But in java, you cant close a port opened by some other application
  4. You can use TCPView to close unreleased ports
Suraj Chandran
  • 24,433
  • 12
  • 63
  • 94