使用Selector实现简单的Sever:
package nio;
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 NIOServer {
private Selector selector;
private ByteBuffer buffer = ByteBuffer.allocate(1024);
private ByteBuffer lBuffer = ByteBuffer.allocate(32);
private ByteBuffer[] bbs = new ByteBuffer[]{buffer,lBuffer};
public NIOServer(int port) throws Exception{
init(port);
}
public void init(int port) throws Exception{
selector = Selector.open();//首先生成一个Selector
ServerSocketChannel schanel = ServerSocketChannel.open();//创建一个ServerSocketChannel
schanel.configureBlocking(false);//设置为非阻塞
schanel.bind(new InetSocketAddress(port));//绑定端口号
schanel.register(selector, SelectionKey.OP_ACCEPT);//在Selector上注册一个接受事件
}
public void start() throws Exception{
while(true){
int num = selector.select();
System.out.println("数量:"+num);
Iterator<SelectionKey> ite=selector.selectedKeys().iterator();
while(ite.hasNext()){
SelectionKey key = ite.next();
handle(key);
ite.remove();//需要自己手动remove事件
}
}
}
public void handle(SelectionKey key) throws Exception{
if(key.isAcceptable()){//接受到一个客户端请求
System.out.println("接受到一个请求");
ServerSocketChannel s = (ServerSocketChannel)key.channel();
SocketChannel socket = s.accept();//获取一个客户端连接SocketChannel
socket.configureBlocking(false);
socket.register(selector, SelectionKey.OP_READ|SelectionKey.OP_WRITE);//在客户端连接上注册READ和WRITE事件
}else
if(key.isReadable()){
System.out.println("接受到一个read请求");
buffer.clear();
SocketChannel socket = (SocketChannel)key.channel();
int r = socket.read(buffer);
System.out.println("读取长度:"+r);
if(-1==r){
socket.close();
key.cancel();
}
System.out.println(new String(buffer.array(),"utf-8"));
}
}
public static void main(String[] args) throws Exception {
NIOServer server = new NIOServer(9999);
server.start();
}
}
package nio;
import jav