views:

127

answers:

4

I have a application that accepts SSL connections on a particular port. When I stop the application from the Websphere Administrative Console and then start it again, I get an exception that complains that the port is still in use. I need to shutdown and restart Websphere entirely to get the application working again.

What is the correct way to stop listening to a port in Java?

+2  A: 

I am not sure as to how it is done in Java, but closing the socket (.close() on the ServerSocket?) will close the port. Still, many operating systems will not let you reuse the same port for about 30 seconds after you have closed it to prevent old messages being read by the new connection.

BobTurbo
+1  A: 

Just close the socket handle, something like yourSocket.close(). This example might help.

KMan
Thanks, but my application accepts incoming connections in a loop. How do I know if Websphere is shutting down my application?
Hippo
If you are opening up a port how would WebSphere come in and close that for you?The Application Server, shuts down your application and the resources that are not managed by the WAS Containers will not be closed as the App Server does not have any clue about them.It should be the application's responsbility to close the ports. Also as mentioned by Bob Turbo, the ports might not be available for a short period after they are closed (this is performed by the OS).
Manglu
@Hippo: Ideally, the application that opens the port is responsible for the graceful close of that port. In your case, you need to keep track(in an array/list, etc) of all of the ports that are being opened in your loop.
KMan
@KMan: Do you mean that I should close the open port(s) in contextDestroyed(), as ZZ Coder described?
Hippo
@Hippo: Important is to close the socket, and yep that could be one place to do that.
KMan
+2  A: 

Create a context listener and register it in web.xml. Then you can close all your open socket in the contextDestroyed() call.

See this for details,

http://publib.boulder.ibm.com/infocenter/wasinfo/v7r0/index.jsp?topic=/com.ibm.websphere.base.doc/info/aes/ae/cweb_sctxl.html

ZZ Coder
A: 
ServerSocket ss = new ServerSocket();
ss.setReuseAddress(true);
ss.bind(port);
EJP