* sends a second request that uses the same connection.
*
* @throws Exception .
*/
private static void examplePersistentConnection() throws Exception {
Peer peer1 = null;
Peer peer2 = null;
try {
final int port1 = 4001;
final int port2 = 4002;
final int timeout = 20;
ChannelServerConfiguration csc = PeerBuilder.createDefaultChannelServerConfiguration();
ChannelClientConfiguration ccc = PeerBuilder.createDefaultChannelClientConfiguration();
csc.pipelineFilter(createFilter());
ccc.pipelineFilter(createFilter());
peer1 = new PeerBuilder(new Number160(RND)).ports(port1).channelClientConfiguration(ccc).channelServerConfiguration(csc).start();
peer2 = new PeerBuilder(new Number160(RND)).ports(port2).start();
//
peer2.objectDataReply(new ObjectDataReply() {
@Override
public Object reply(final PeerAddress sender, final Object request) throws Exception {
return "world!";
}
});
String sentObject = "Hello";
FutureDirect fd = peer1.sendDirect(peer2.peerAddress()).object(sentObject).start();
System.out.println("send " + sentObject);
fd.awaitUninterruptibly();
System.out.println("received " + fd.object() + " connections: "
+ ccohTCP.total()+ "/"+ccohUDP.total());
// keep the connection for 20s alive. Setting -1 means to keep it open as long as possible
FuturePeerConnection futurePeerConnection = peer1.createPeerConnection(peer2.peerAddress(), timeout);
fd = peer1.sendDirect(futurePeerConnection).object(sentObject).start();
System.out.println("send " + sentObject);
fd.awaitUninterruptibly();
System.out.println("received " + fd.object() + " connections: "
+ ccohTCP.total()+ "/"+ccohUDP.total());
// we reuse the connection
fd = peer1.sendDirect(futurePeerConnection).object(sentObject).start();
System.out.println("send " + sentObject);
fd.awaitUninterruptibly();
System.out.println("received " + fd.object() + " connections: "
+ ccohTCP.total()+ "/"+ccohUDP.total());
// now we don't want to keep the connection open anymore:
futurePeerConnection.close();
} finally {
if (peer1 != null) {
peer1.shutdown();
}
if (peer2 != null) {
peer2.shutdown();
}
}
}