在继续深入netty之前,还是补习一下java的selector的使用吧,没想到java里面用起来跟epoll什么的也差不太多。。。
好吧,废话少说,直接上代码了,反正也比较的简单,也就不细说了。。。。。
package fjs;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
public class Fjs {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
Selector sel = Selector.open();
ServerSocketChannel sc = ServerSocketChannel.open();
sc.configureBlocking(false);
sc.socket().bind(new InetSocketAddress(8000));
sc.register(sel, SelectionKey.OP_ACCEPT); //相当于是注册selector,并且注册事件是accept事件
while (true) {
sel.select();
Iterator<SelectionKey> ki = sel.selectedKeys().iterator(); //用于遍历所有产生的事件
while (ki.hasNext()) {
SelectionKey key = ki.next();
if (key.isAcceptable()) {
ServerSocketChannel channel = (ServerSocketChannel) key.channel();
SocketChannel ss = channel.accept();
if (ss != null) {
ss.configureBlocking(false);
ss.register(sel, SelectionKey.OP_READ);
}
}
if (key.isReadable()) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
SocketChannel socketChannel = (SocketChannel) key.channel();
socketChannel.read(buffer);
buffer.flip();
while (buffer.hasRemaining())
System.out.print((char)buffer.get());
socketChannel.register(sel, SelectionKey.OP_WRITE);
}
if (key.isWritable()) {
SocketChannel ch = (SocketChannel) key.channel();
ByteBuffer buff = ByteBuffer.wrap("hello world".getBytes());
ch.write(buff);
ch.close();
}
}
}
}
}