package org.infinispan.test;

import org.jgroups.Address;
import org.jgroups.blocks.TCPConnectionMap;
import org.jgroups.stack.IpAddress;
import org.jgroups.util.DefaultThreadFactory;

import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * @author Dan Berindei
 * @since 8.1
 */
public class SocketConnectionTimeoutTest {
   public static void main(String[] args) throws Exception {
      String targetHost = "8.8.8.198";
      int targetPort = 9999;

      long start = System.nanoTime();
      try {
         Socket s = new Socket();
         s.connect(new InetSocketAddress(targetHost, targetPort), 300);
      } catch (Exception e) {
         System.err.println(e);
      } finally {
         long duration = System.nanoTime() - start;
         System.out.printf("Connect took %.3f s\n", 1. * duration / 1000000000);
      }

      TCPConnectionMap.Receiver dummy = new TCPConnectionMap.Receiver() {
         public void receive(Address sender, byte[] data, int offset, int length) {
         }
      };

      InetAddress loopback_addr = InetAddress.getLoopbackAddress();
      TCPConnectionMap ct1 =
            new TCPConnectionMap("ConnectionMapTest1", new DefaultThreadFactory("ConnectionMapTest", true),
                                 null, dummy, loopback_addr, null, 0, targetPort, targetPort);
      ct1.setSocketConnectionTimeout(300);
      ct1.start();

      Address target = new IpAddress(targetHost, targetPort);
      byte[] data = new byte[] {(byte) 0xf0};
      start = System.nanoTime();
      try {
         ct1.send(target, data, 0, data.length);
      } catch (Exception e) {
         System.err.println(e);
      } finally {
         long duration = System.nanoTime() - start;
         System.out.printf("Connect took %.3f s\n", 1. * duration / 1000000000);
      }
   }
}
