简体   繁体   中英

Java - How to close reset the socket which was initialized by my application and on the fly re-open it? both in TCP or UDP

I have the following application which get launched as below:

Runtime.getRuntime().exec("java -cp /var/dist/Test.jar System.V PDP-11");

It has 10 to 20 second of task also it contain TCP/UDP server on port 1965 . Once that task is complete, my another hand sends an TCP byte to shutdown the System.V

Runtime.getRuntime().exec("java -cp /var/dist/Test.jar System.V PDP-11/20");

Within less then 1 seconds another action executes as above, but that fails because port 1965 is already in use. But it was killed using System.exit(0)

How do i resolve that? So that it does not say "already in use port"? It seems like it takes lot of time to de-initialize the TCP or UDP ports that was listening via Java. (where nc -l port get lot faster killed).

Follow up:

i tried following but still it takes too while to get that port available (Linux OS).

byte[] buf = new byte[50];

sock.setSoTimeout(100);

It takes some time for OS to "notice" that port can be used again - even if you close the socket and kill the application. Problem can be solved with following code:

ServerSocket ss = ... //initialization of socket listening on port 1965
ss.setReuseSocket(true);

Please remember that code above is only a hint for OS that is should free port as fast as possible. Some exotic implementations of TCP stack might not honour this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM