Package org.dellroad.stuff.net
Class PersistentSocketConnection
java.lang.Object
org.dellroad.stuff.net.PersistentConnection<Socket>
org.dellroad.stuff.net.PersistentSocketConnection
Maintains a persistent
Socket
connection to a remote server, automatically reconnecting when the connection fails.
Subclasses need only override handleConnection()
.
-
Field Summary
Fields inherited from class org.dellroad.stuff.net.PersistentConnection
DEFAULT_MAX_RESTART_DELAY, DEFAULT_MIN_RESTART_DELAY, log
-
Constructor Summary
-
Method Summary
Modifier and TypeMethodDescriptionprotected void
cleanupConnection
(Socket socket) Perform cleanup after a server connection ends.protected Socket
Create a new server connection.protected Socket
Create theSocket
to use for a new connection.Get the address to which this instance should connect.void
setServerAddress
(SocketAddress serverAddress) Configure the address to which this instance should connect.void
start()
Start this instance.Methods inherited from class org.dellroad.stuff.net.PersistentConnection
connectionEnded, connectionFailed, connectionSuccessful, getMaxRestartDelay, getMinRestartDelay, getThreadName, handleConnection, isRunning, setMaxRestartDelay, setMinRestartDelay, started, stop, stopped
-
Constructor Details
-
PersistentSocketConnection
public PersistentSocketConnection()
-
-
Method Details
-
getServerAddress
Get the address to which this instance should connect.- Returns:
- remote server address
-
setServerAddress
Configure the address to which this instance should connect.Required property.
- Parameters:
serverAddress
- remote server address
-
start
public void start()Description copied from class:PersistentConnection
Start this instance. This starts the background thread, which initiates the first connection attempt.If this instance is already started, nothing happens.
- Overrides:
start
in classPersistentConnection<Socket>
-
createConnection
Create a new server connection.The implementation in
PersistentSocketConnection
creates a socket viacreateSocket()
and connects the socket to the configured server.- Specified by:
createConnection
in classPersistentConnection<Socket>
- Returns:
- connected socket
- Throws:
IOException
- if the connection attempt failsInterruptedException
- if the current thread is interrupted
-
cleanupConnection
Perform cleanup after a server connection ends.The implementation in
PersistentSocketConnection
ensures the socket is closed.- Overrides:
cleanupConnection
in classPersistentConnection<Socket>
- Parameters:
socket
- socket returned fromcreateConnection()
when this connection was created
-
createSocket
Create theSocket
to use for a new connection. The socket should not be connected yet.The implementation in
PersistentSocketConnection
creates a normalSocket
and sets the keep-alive flag to ensure connection failures are detected promptly. Subclasses may override to configure the socket differently.- Returns:
- new socket
- Throws:
IOException
- if socket creation fails
-