server端:
public class NIOServer {
private int i = 1;
private Selector selector = null;
private SocketChannel client = null;
public NIOServer(int port) throws IOException {
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking(false);
ssc.socket().bind(new InetSocketAddress(port));
selector = Selector.open();
ssc.register(selector, SelectionKey.OP_ACCEPT);
}
private void listen() throws Exception {
while(true) {
int i = selector.select();
Set<SelectionKey> selectedKeys = null;
if(i>0){
selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectedKeys.iterator();
while(iterator.hasNext()) {
SelectionKey key = iterator.next();
iterator.remove();
handleKey(key);
}
}
}
}
private void handleKey(SelectionKey key) throws Exception {
if(key.isAcceptable()) {
ServerSocketChannel ssc = (ServerSocketChannel) key.channel();
client = ssc.accept();
client.configureBlocking(false);
client.register(selector, SelectionKey.OP_READ);
}else if(key.isReadable()) {
ByteBuffer bb = ByteBuffer.allocate(1023);
client.read(bb);
System.out.println("server读:"+new String(bb.array(),0,bb.position()));
client.register(selector, SelectionKey.OP_WRITE);
}else if(key.isWritable()) {
ByteBuffer bb = ByteBuffer.allocate(1024);
bb.put(("dataFormServer"+i++).getBytes());
bb.flip();
client.write(bb);
client.register(selector,SelectionKey.OP_READ);
}
}
public static void main(String[] args) throws Exception {
new NIOServer(7080).listen();
}
}
client端:
public class NIOClient {
private static int j = 1;
public static void main(String[] args) throws Exception {
SocketChannel sc = SocketChannel.open();
sc.configureBlocking(false);
sc.connect(new InetSocketAddress("127.0.0.1",7080));
Selector selector = Selector.open();
sc.register(selector, SelectionKey.OP_CONNECT);
while(true) {
int i = selector.select();
if(i>0) {
Set<SelectionKey> selectedKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectedKeys.iterator();
while(iterator.hasNext()) {
SelectionKey key = iterator.next();
iterator.remove();///与下面注释关联
if(key.isConnectable()) {
if(sc.isConnectionPending()) {
sc.finishConnect();
sc.register(selector, SelectionKey.OP_WRITE);
}
}else if(key.isWritable()) {
ByteBuffer bb = ByteBuffer.allocate(1024);
bb.put(("dataFromClient:"+j++).getBytes());
bb.flip();
sc.write(bb);//与上面注释关联,如果remove,则不会注销,因为只会注销set中有的集合
sc.register(selector, SelectionKey.OP_READ);
}else if(key.isReadable()) {
ByteBuffer bb = ByteBuffer.allocate(1024);
sc.read(bb);
System.out.println("client 读:"+new String(bb.array(),0,bb.position()));
sc.register(selector,SelectionKey.OP_WRITE);
}
}
}
}
}
}