RT
@Test
public void channelTest() throws IOException{
SocketChannel client = SocketChannel.open();
//Attention here:
//local connection is established immediately so connectionPending is false here
System.out.println("is connection pending:"+client.isConnectionPending());
client.connect(new InetSocketAddress("localhost", 8000));
client.configureBlocking(false);
client.write(ByteBuffer.wrap("hello".getBytes()));
ByteBuffer bf = ByteBuffer.allocate(5);
client.read(bf);
System.out.println(bf);
//pending means is going to be connected but has not been connected
//Tells whether or not a connection operation is in progress on this channel.
System.out.println("is connection pending:"+client.isConnectionPending());
System.out.println("is connected:"+client.isConnected());
// no need to put finishConnect if connection is on this computer
// client1.finishConnect();
System.out.println("if client1 finished connecting:"+client.isConnected());
Selector selector = Selector.open();
client.register(selector, SelectionKey.OP_WRITE|SelectionKey.OP_READ|SelectionKey.OP_CONNECT);
//selector has a set of ready channels
int readyChannels = selector.select();
System.out.println("ready channels:"+readyChannels);
Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();
while(keyIter.hasNext()){
SelectionKey key = keyIter.next();
//SocketChannel sc = (SocketChannel) key.channel();
// sc.write(ByteBuffer.wrap("hello".getBytes()));
System.out.println("interest ops:"+key.interestOps());
System.out.println("ready ops:"+key.readyOps());
keyIter.remove();
if(key.isAcceptable()){
System.out.println("acceptable");
System.out.println((key.readyOps()&SelectionKey.OP_ACCEPT)!=0);
}
if(key.isReadable()){
System.out.println("readable");
System.out.println((key.readyOps()&SelectionKey.OP_READ)!=0);
}
if(key.isWritable()){
System.out.println("writable");
System.out.println((key.readyOps()&SelectionKey.OP_WRITE)!=0);
}
if(key.isConnectable()){
System.out.println("connectable");
System.out.println((key.readyOps()&SelectionKey.OP_CONNECT)!=0);
}
}
}
输出为
is connection pending:false
java.nio.HeapByteBuffer[pos=0 lim=5 cap=5]
is connection pending:false
is connected:true
if client1 finished connecting:true
ready channels:1
interest ops:13
ready ops:4
writable
true