3

Look at the following test:

public class AsynchronousSocketTest {
  static PrintStream out=System.out;
  public static  void main(String[] args) throws IOException, InterruptedException, ExecutionException {
    int port=9008;
    InetSocketAddress addr=new InetSocketAddress("localhost", port);
    AsynchronousChannelGroup acg=AsynchronousChannelGroup.withThreadPool(Executors.newFixedThreadPool(1));
    // server not working, client trying to connect
    AsynchronousSocketChannel conn1=AsynchronousSocketChannel.open(acg);
    Future<Void> connfut1 = conn1.connect(addr); // no error, question 1
    Thread.sleep(100);
    out.println("connected1:"+connfut1.isDone());
    // start server
    AsynchronousServerSocketChannel assch=AsynchronousServerSocketChannel.open(acg);
    assch.bind(addr);
    // accept
    Future<AsynchronousSocketChannel> accfut1 = assch.accept();
    Thread.sleep(100);
    out.println("accepted1:"+accfut1.isDone());  // did not accept, question 2
    out.println("connected1:"+connfut1.isDone());  // did not connected
    // try new client connection
    AsynchronousSocketChannel conn2=AsynchronousSocketChannel.open(acg);
    Future<Void> connfut2 = conn2.connect(addr);
    Thread.sleep(100);
    out.println("connected2:"+connfut2.isDone()); // connected
    out.println("accepted1:"+accfut1.isDone());  // accepted
    // accept
    Future<AsynchronousSocketChannel> accfut2 = assch.accept();
    Thread.sleep(100);
    out.println("accepted2:"+accfut2.isDone()); // not accepted
    out.println("connected1:"+connfut1.isDone()); // still waiting
  }
}

On Windows java 1.7.0_05 it prints:

 connected1:false
 accepted1:false
 connected1:false
 connected2:true
 accepted1:true
 accepted2:false
 connected1:false

The questions are:

  1. why does the first conn1.connect(addr) not fail, although the server port is not bound yet?
  2. why does the first assch.accept() not accept the already pending client connection?

I've read JDK's javadoc and could not find answers.

4

0 回答 0