Apache MINA NioSocketAcceptor类的实现

时间:2023-03-10 06:03:06
Apache MINA NioSocketAcceptor类的实现

NioSocketAcceptor 继承AbstractPollingIoAcceptor,实现SocketAcceptor接口

public final class NioSocketAcceptor extends AbstractPollingIoAcceptor<NioSession, ServerSocketChannel> implements SocketAcceptor {}

成员变量:

private volatile Selector selector;

volatile 修饰词的使用:http://developer.zdnet.com.cn/2007/1107/612888.shtml

实现方法:

    @Override
protected void init() throws Exception {
//初始化selector
selector = Selector.open();
}
 @Override
protected ServerSocketChannel open(SocketAddress localAddress) throws Exception {
// 创建ServerSocket通道
ServerSocketChannel channel = ServerSocketChannel.open(); boolean success = false; try {
// 设置非阻塞的socket通道
channel.configureBlocking(false); // 获取ServerScoket
ServerSocket socket = channel.socket(); // Set the reuseAddress flag accordingly with the setting
socket.setReuseAddress(isReuseAddress()); // 绑定监听地址和端口号
socket.bind(localAddress, getBacklog()); // 在selector中注册
channel.register(selector, SelectionKey.OP_ACCEPT);
success = true;
} finally {
if (!success) {
close(channel);
}
}
return channel;
}
    @Override
protected int select() throws Exception {
return selector.select();
}
    @Override
protected Iterator<ServerSocketChannel> selectedHandles() {
return new ServerSocketChannelIterator(selector.selectedKeys());
}
    @Override
protected void close(ServerSocketChannel handle) throws Exception {
SelectionKey key = handle.keyFor(selector); if (key != null) {
key.cancel();
} handle.close();
}

        public ServerSocketChannel next() {
SelectionKey key = iterator.next(); if (key.isValid() && key.isAcceptable()) {
return (ServerSocketChannel) key.channel();
} return null;
}