publicclassNServer{//用于检测所有Channel状态的SelectorprivateSelectorselector=null;staticfinalintPORT=30000;privateCharsetcharset=Charset.forName("UTF-8");publicvoidinit(...
public class NServer
{
// 用于检测所有Channel状态的Selector
private Selector selector = null;
static final int PORT = 30000;
private Charset charset = Charset.forName("UTF-8");
public void init()throws IOException
{
selector = Selector.open();
// 通过open方法来打开一个未绑定的ServerSocketChannel实例
ServerSocketChannel server = ServerSocketChannel.open();
InetSocketAddress isa = new InetSocketAddress("127.0.0.1", PORT);
server.bind(isa);
// 设置ServerSocket以非阻塞方式工作
server.configureBlocking(false);
// 将server注册到指定Selector对象
server.register(selector, SelectionKey.OP_ACCEPT);
while (selector.select() > 0)
{
for (SelectionKey sk : selector.selectedKeys())
{
// 从selector上的已选择Key集中删除正在处理的SelectionKey
selector.selectedKeys().remove(sk); //①
// 如果sk对应的Channel包含客户端的连接请求
if (sk.isAcceptable()) //②
{
// 调用accept方法接受连接,产生服务器端的SocketChannel
SocketChannel sc = server.accept();
// 设置采用非阻塞模式
sc.configureBlocking(false);
// 将该SocketChannel也注册到selector
sc.register(selector, SelectionKey.OP_READ);
// 将sk对应的Channel设置成准备接受其他请求
sk.interestOps(SelectionKey.OP_ACCEPT);
}
if (sk.isReadable()) //③
{
// 获取该SelectionKey对应的Channel,该Channel中有可读的数据
SocketChannel sc = (SocketChannel)sk.channel();
// 定义准备执行读取数据的ByteBuffer
ByteBuffer buff = ByteBuffer.allocate(1024);
String content = "";
// 开始读取数据
try
{
while(sc.read(buff) > 0)
{
buff.flip();
content += charset.decode(buff);
}
System.out.println("读取的数据:" + content);
sk.interestOps(SelectionKey.OP_READ);
}
展开