net.zortrium.p2proto
Class Connection

java.lang.Object
  extended by net.zortrium.p2proto.Connection

public final class Connection
extends Object

A connection to send messages to a remote peer. In general, the peer should be listening on the specified port via a PeerListener. Unsolicited messages may be sent over the connection (at which point they will be handled by the remote PeerListener handler), and responses to these messages are automatically retrieved and returned, independent of issues like network delays and the order of message arrival.

Messages may optionally request that a response is returned from the server, in which case the connection will wait for a response until a default or specified timeout duration as passed. In general, the simplest way to do this is to design the application such that a given message type either always returns a response or never does. If a response times out (raising a PeerErrorException) but the missed response is subsequently received, it is simply discarded.

Messages may be sent both synchronously and asynchronously and may include timeouts and custom error handlers. Connections are thread-safe by default. This class also contains caching methods to facilitate reuse of Connection objects. However, use of the caching methods are optional and users are free to manage their connections manually if desired.

Author:
Sean Barker - www.zortrium.net
See Also:
Msg, PeerListener

Constructor Summary
Connection(InetAddress remoteAddress, int port)
          Set up the new socket connection to the given host.
Connection(String remoteAddress, int port)
          Convenience constructor that calls InetAddress.getByName(String) and passes it to Connection(InetAddress, int).
 
Method Summary
 void close()
          Close the connection and all internal streams.
 boolean equals(Object obj)
          Two connections are equal if they are connected to the same address on the same port.
 InetAddress getAddress()
          Get the remote address of this connection.
static Connection getCached(InetAddress remoteAddress, int port)
          Get a cached connection to the given address and port.
static Connection getCached(String remoteAddress, int port)
          Performs a hostname lookup and calls getCached(InetAddress, int).
 long getDefaultTimeout()
          Get the default timeout (in ms) for receiving response messages.
 int getPort()
          Get the remote port of this connection.
 int hashCode()
           
 boolean isClosed()
          Check whether the connection is still active.
 void send(Msg msg)
          Send a message and do not wait for a response message.
 void sendAsync(Msg msg)
          Send a message asynchronously and disregard any responses received.
 void sendAsync(Msg msg, MsgCallback callback)
          Send a message asynchronously and disregard any responses received.
 Msg sendRequest(Msg msg)
          Send a message and block until either a response message is received or the default timeout has passed.
 Msg sendRequest(Msg msg, long timeout)
          Send a message and block until either a response message is received or the specified timeout (in ms) has passed.
 void sendRequestAsync(Msg msg, MsgCallback callback)
          Send a message asynchronously and call the given handler when a response is received, the default timeout has elapsed, or a send error occurs.
 void sendRequestAsync(Msg msg, MsgCallback callback, long timeout)
          Send a message asynchronously and call the given handler when a response is received, the specified timeout (in ms) has passed, or a send error occurs.
 void setDefaultTimeout(long timeout)
          Set the default timeout (in ms) for receiving response messages, used by sendRequest(Msg) and sendRequestAsync(Msg, MsgCallback) .
 void setThreadSafety(boolean safety)
          Set whether the connection performs internal synchronization on the outgoing message queue.
 String toString()
           
 
Methods inherited from class java.lang.Object
clone, finalize, getClass, notify, notifyAll, wait, wait, wait
 

Constructor Detail

Connection

public Connection(InetAddress remoteAddress,
                  int port)
           throws IOException
Set up the new socket connection to the given host.

Parameters:
remoteAddress - Remote host to connect to.
port - Remote port to connect to.
Throws:
IOException - If the connection failed.

Connection

public Connection(String remoteAddress,
                  int port)
           throws IOException
Convenience constructor that calls InetAddress.getByName(String) and passes it to Connection(InetAddress, int).

Parameters:
remoteAddress - Textual IP address or hostname to connect to.
port - Remote port to connect to.
Throws:
IOException - If the host lookup or connection failed.
Method Detail

getCached

public static Connection getCached(InetAddress remoteAddress,
                                   int port)
                            throws IOException
Get a cached connection to the given address and port. If no such connection exists in the cache, or if the cached connection is closed, a new connection is created, added to the cache, and returned.

This method is thread-safe; however, concurrent calls for the same address and port are NOT guaranteed to return the same Connection. If the specified connection is not cached, simultaneous calls may create more than one new connection (however, only one such connection will end up in the cache).

Parameters:
remoteAddress - The remote address to connect to.
port - The remote port to connect to.
Returns:
A connection to the given address and port.
Throws:
IOException - If establishing a new connection fails.

getCached

public static Connection getCached(String remoteAddress,
                                   int port)
                            throws IOException
Performs a hostname lookup and calls getCached(InetAddress, int).

Throws:
IOException

setThreadSafety

public void setThreadSafety(boolean safety)
Set whether the connection performs internal synchronization on the outgoing message queue. This prevents outgoing message overlap and ensures that messages are received intact. Thread safety is enabled by default. You may disable thread safety for increased performance only if (1) you are not sending asynchronous messages, and (2) you are either only sending messages on a single thread or are performing your own synchronization on all sending threads.

Parameters:
safety - True to (re)enable thread safety and false to disable.

setDefaultTimeout

public void setDefaultTimeout(long timeout)
Set the default timeout (in ms) for receiving response messages, used by sendRequest(Msg) and sendRequestAsync(Msg, MsgCallback) . The default setting is 5 seconds (5000 ms).

Parameters:
timeout - The new default timeout (in ms).

getDefaultTimeout

public long getDefaultTimeout()
Get the default timeout (in ms) for receiving response messages. The default setting is 5 seconds (5000 ms).

Returns:
The current default timeout (in ms).

close

public void close()
Close the connection and all internal streams.


isClosed

public boolean isClosed()
Check whether the connection is still active. Returns true if the connection has been closed.

Returns:
Whether the connection is active.

getAddress

public InetAddress getAddress()
Get the remote address of this connection.

Returns:
The remote address.

getPort

public int getPort()
Get the remote port of this connection.

Returns:
The remote port.

sendAsync

public void sendAsync(Msg msg)
Send a message asynchronously and disregard any responses received. Send errors are caught and ignored. If you need to handle send errors, use sendAsync(Msg, MsgCallback).

Parameters:
msg - The message to send.

sendAsync

public void sendAsync(Msg msg,
                      MsgCallback callback)
Send a message asynchronously and disregard any responses received. Send errors are passed to the given callback. Note that since no response is expected when using this method, the callback is only used in the event of a send error, via MsgCallback.handleException(IOException).

Parameters:
msg - The message to send.
callback - The callback handling send errors.

sendRequestAsync

public void sendRequestAsync(Msg msg,
                             MsgCallback callback)
Send a message asynchronously and call the given handler when a response is received, the default timeout has elapsed, or a send error occurs.

Parameters:
msg - The message to send.
callback - The handler to call when a response is received or the response times out.

sendRequestAsync

public void sendRequestAsync(Msg msg,
                             MsgCallback callback,
                             long timeout)
Send a message asynchronously and call the given handler when a response is received, the specified timeout (in ms) has passed, or a send error occurs.

Parameters:
msg - The message to send.
callback - The handler to call when a response is received or the response times out.
timeout - The duration to wait for a response (in ms).

send

public void send(Msg msg)
          throws IOException
Send a message and do not wait for a response message. May block if many other messages are in queue to send across this connection.

Parameters:
msg - The message to send.
Throws:
IOException - If a send error occurs.

sendRequest

public Msg sendRequest(Msg msg)
                throws PeerTimeoutException,
                       PeerErrorException,
                       IOException
Send a message and block until either a response message is received or the default timeout has passed. Throws an exception if a timeout occurs.

Parameters:
msg - The request message to send.
Returns:
The response message.
Throws:
PeerTimeoutException - If the response times out.
PeerErrorException - If an error response is received.
IOException - If a send error occurs.

sendRequest

public Msg sendRequest(Msg msg,
                       long timeout)
                throws PeerTimeoutException,
                       PeerErrorException,
                       IOException
Send a message and block until either a response message is received or the specified timeout (in ms) has passed. A timeout of 0 will wait forever until a response is received. Throws an exception if a timeout occurs.

Parameters:
msg - The request message to send.
timeout - The response timeout (in ms).
Returns:
The response message.
Throws:
PeerTimeoutException - If a response is not received in time.
PeerErrorException - If an error response is received.
IOException - If a send error occurs.

equals

public boolean equals(Object obj)
Two connections are equal if they are connected to the same address on the same port.

Overrides:
equals in class Object

hashCode

public int hashCode()
Overrides:
hashCode in class Object

toString

public String toString()
Overrides:
toString in class Object