开发者

Running a program in succession on the same port

开发者 https://www.devze.com 2023-03-08 11:53 出处:网络
I am running some java code on CentOS 5 java Something.java & that creates a socket on a certain port....say 9090..however, the code doesn\'t run completely and so I Ctrl-C out of it.

I am running some java code on CentOS 5

java Something.java &

that creates a socket on a certain port....say 9090..however, the code doesn't run completely and so I Ctrl-C out of it.

When I try running the program again it errors out saying it cannot connect to the port 9090.

When I change the port number to some arbitrary thing like 9010...everything works again (except for the fact that Something.java gets stuck)....churn and repeat

What's going on? I'd like to be able to use one consistent port for this stuff...is 开发者_Go百科there some background process I am not getting rid of everytime?

Thanks!


This might happen because the OS has some quarantine delay until another process can reuse the address.

The C library provides the socket option SO_REUSEADDR which can be set to avoid this. A quick web search indicates that setReuseAddress(boolean) in java.net.ServerSocket can be used to set this option.


It may take some time for the JVM to actually finish the program and release the socket.

You can manually close the socket when the software is terminated by ctrl-c with Runtime.getRuntime().addShutdownHook(...), which I greatly recommend for all the software that is running in the background and uses sockets. Should help.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号