public class TestNio {
public static void main(String[] args) throws IOException {
Selector selector = Selector.open();
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.socket().bind(new InetSocketAddress("192.168.27.48", 7777));
ssc.configureBlocking(false);
ssc.register(selector, SelectionKey.OP_ACCEPT);
while(true){
int n = selector.select();
if(n > 0){
Iterator<SelectionKey> ite = selector.selectedKeys().iterator();
while(ite.hasNext()){
SelectionKey k = ite.next();
ite.remove();
if(k.isAcceptable()){
SocketChannel s = ((ServerSocketChannel)k.channel()).accept();
s.configureBlocking(false);
System.out.println("accept:" + s.socket().getPort() + " s:" + s);
s.register(selector, SelectionKey.OP_WRITE);
}else if(k.isReadable()){
SocketChannel sc = (SocketChannel) k.channel();
ByteBuffer dst = ByteBuffer.allocate(1024);
sc.read(dst);
System.out.println("str:" + dst.toString());
sc.keyFor(selector).cancel();
sc.keyFor(selector).interestOps(SelectionKey.OP_WRITE);
}else if(k.isWritable()){
SocketChannel sc = (SocketChannel) k.channel();
ByteBuffer b = ByteBuffer.allocate(12);
b.put(new String("repaly").getBytes("utf-8"));
b.flip();
sc.write(b);
sc.keyFor(selector).interestOps(SelectionKey.OP_READ);
}
}
}
}
}
}
public static void main(String[] args) throws IOException {
Selector selector = Selector.open();
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.socket().bind(new InetSocketAddress("192.168.27.48", 7777));
ssc.configureBlocking(false);
ssc.register(selector, SelectionKey.OP_ACCEPT);
while(true){
int n = selector.select();
if(n > 0){
Iterator<SelectionKey> ite = selector.selectedKeys().iterator();
while(ite.hasNext()){
SelectionKey k = ite.next();
ite.remove();
if(k.isAcceptable()){
SocketChannel s = ((ServerSocketChannel)k.channel()).accept();
s.configureBlocking(false);
System.out.println("accept:" + s.socket().getPort() + " s:" + s);
s.register(selector, SelectionKey.OP_WRITE);
}else if(k.isReadable()){
SocketChannel sc = (SocketChannel) k.channel();
ByteBuffer dst = ByteBuffer.allocate(1024);
sc.read(dst);
System.out.println("str:" + dst.toString());
sc.keyFor(selector).cancel();
sc.keyFor(selector).interestOps(SelectionKey.OP_WRITE);
}else if(k.isWritable()){
SocketChannel sc = (SocketChannel) k.channel();
ByteBuffer b = ByteBuffer.allocate(12);
b.put(new String("repaly").getBytes("utf-8"));
b.flip();
sc.write(b);
sc.keyFor(selector).interestOps(SelectionKey.OP_READ);
}
}
}
}
}
}