import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import com.sun.nio.sctp.MessageInfo;
import com.sun.nio.sctp.SctpMultiChannel;

public class ESctpMC {

    static int NUM = 10;

    public static void main(String[] args) throws Exception {
        int port = 12345;
        if (args.length == 1) {
            try {
                port = Integer.parseInt(args[0]);
            } catch (Exception e) {
            }
        }
        new Server(port).start();

        Thread.sleep(100); // wait for server ready

        for (int i = 0; i < 20; ++i) {
            System.out.println(i);
            doIt(port);
            Thread.sleep(200);
        }
        System.out.println("end");

        long myPid = ProcessHandle.current().pid();
        ProcessBuilder pb = new ProcessBuilder(
                "lsof", "-U", "-a", "-p", Long.toString(myPid));
        pb.inheritIO();
        Process p = pb.start();
        p.waitFor();

        System.exit(0);
    }

    static void doIt(int port) throws Exception {
        InetSocketAddress sa = new InetSocketAddress("localhost", port);

        for (int i = 0; i < NUM; ++i) {
            System.out.println("  " + i);
            SctpMultiChannel channel = SctpMultiChannel.open();
            channel.configureBlocking(false);
            MessageInfo info = MessageInfo.createOutgoing(sa, 0);

            channel.close();

            Thread.sleep(200);
        }
    }

    static class Server extends Thread {
        int port;

        Server(int port) {
            this.port = port;
        }

        @Override
        public void run() {
            try {
                SctpMultiChannel sm = SctpMultiChannel.open();
                InetSocketAddress sa = new InetSocketAddress("localhost", port);
                sm.bind(sa);
                ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
                MessageInfo info = sm.receive(buffer, null, null);
                sm.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
