public void testBlockingConnect() throws Exception {
   setupConnection();
   AbstractNBSocket socket = udpSelectorProvider.openSocketChannel().socket();
   socket.connect(new InetSocketAddress("127.0.0.1", PORT_1));
   assertTrue(socket.isConnected());
   socket.close();
   Thread.sleep(500);
   assertFalse(socket.isConnected());
 }
 public void testNonBlockingConnect() throws Exception {
   setupConnection();
   AbstractNBSocket socket = udpSelectorProvider.openSocketChannel().socket();
   StubConnectObserver observer = new StubConnectObserver();
   socket.connect(new InetSocketAddress("127.0.0.1", PORT_1), 5000, observer);
   observer.waitForResponse(5500);
   assertTrue(socket.isConnected());
   assertSame(socket, observer.getSocket());
   assertFalse(observer.isShutdown());
   assertNull(observer.getIoException());
   socket.close();
   Thread.sleep(500);
   assertFalse(observer.isShutdown()); // doesn't get both connect & shutdown
   assertFalse(socket.isConnected());
 }
  public void testDelayedGetInputStream() throws Exception {
    StubConnectObserver stub = setupConnection();

    InetSocketAddress addr = new InetSocketAddress("127.0.0.1", PORT_1);
    AbstractNBSocket socket = udpSelectorProvider.openSocketChannel().socket();
    socket.setSoTimeout(1000);
    socket.connect(addr);

    stub.waitForResponse(5000);
    Socket accepted = stub.getSocket();
    assertNotNull(accepted);

    byte[] rnd = new byte[100];
    new Random().nextBytes(rnd);
    accepted.getOutputStream().write(rnd); // this'll go immediately into the buffer

    ICROAdapter icro = new ICROAdapter();
    ByteBuffer read = icro.getReadBuffer();
    assertEquals(0, read.position());

    socket.setReadObserver(icro);
    Thread.sleep(500); // let NIODispatcher to its thang.

    assertEquals(100, read.position()); // data was transferred to the reader.
    for (int i = 0; i < 100; i++) assertEquals(rnd[i], read.get(i));

    InputStream stream = socket.getInputStream();
    byte[] readData = new byte[100];
    assertEquals(100, stream.read(readData));
    assertEquals(rnd, readData);

    assertEquals(0, read.position()); // moved to the InputStream

    new Random().nextBytes(rnd);
    accepted.getOutputStream().write(rnd); // write some more, make sure it goes to stream

    Thread.sleep(500);
    assertEquals(0, read.position());
    assertEquals(100, stream.read(readData));
    assertEquals(rnd, readData);

    socket.close();
  }