In general, it is better to maintain a long-running ServerSocket
that serves multiple requests, as others have already answered and commented. However, I have found that sometimes there is a legitimate need to stop and start a server in rapid succession. One example is an integration test suite that involves stopping and restarting the server in different configurations to repeat test runs.
If you really have this need, then you might be interested in ServerSocket#setReuseAddress(boolean)
.
Enable/disable the SO_REUSEADDR socket option.
When a TCP connection is closed the connection may remain in a timeout state for a period of time after the connection is closed (typically known as the TIME_WAIT state or 2MSL wait state). For applications using a well known socket address or port it may not be possible to bind a socket to the required SocketAddress if there is a connection in the timeout state involving the socket address or port.
Enabling SO_REUSEADDR prior to binding the socket using bind(SocketAddress) allows the socket to be bound even though a previous connection is in a timeout state.
This ultimately enables the SO_REUSEADDR
socket option. One source of information for more details on these socket options is the Linux socket
man page.
However, please be aware that the exact perceived behavior can very greatly across different platforms. In particular, beware of the extremely different and dangerous behavior of this setting on Windows, as documented in the MSDN article Using SO_REUSEADDR and SO_EXCLUSIVEADDRUSE. Basically, SO_REUSEADDR
on Windows can allow any arbitrary process to "steal" a socket already in use by another process, resulting in indeterminate behavior.
The SO_REUSEADDR socket option allows a socket to forcibly bind to a port in use by another socket. The second socket calls setsockopt with the optname parameter set to SO_REUSEADDR and the optval parameter set to a boolean value of TRUE before calling bind on the same port as the original socket. Once the second socket has successfully bound, the behavior for all sockets bound to that port is indeterminate. For example, if all of the sockets on the same port provide TCP service, any incoming TCP connection requests over the port cannot be guaranteed to be handled by the correct socket — the behavior is non-deterministic. A malicious program can use SO_REUSEADDR to forcibly bind sockets already in use for standard network protocol services in order to deny access to those service. No special privileges are required to use this option.
I advise people to think carefully and make sure you're confident with this setting rather than blindly turning it on. There is also a phenomenal prior question and answer about the relevant socket options:
Socket options SO_REUSEADDR and SO_REUSEPORT, how do they differ? Do they mean the same across all major operating systems?