NIO-ServerSocketChannel详解

ServerSocketChannel类似于SocketChannel[参考:http://shift-alt-ctrl.iteye.com/blog/1840409],只不过ServerSocketChannel使用server端.ServerSocketChannel是ServerSocket + Selector的高层封装.可以通过socket()方法获得与其关联的ServerSocket.

 

  • public abstract SocketChannel open():打开channel.通过底层SelectorProvider.provider().openServerSocketChannel();此后需要进行bind(InetAddress)来建立本地连接.
  • public final int validOps():返回一个有效的操作集,此通道只支持OP_ACCEPT
  • public abstract ServerSocket socket():获取关联的ServerSocket.
  • public abstract SocketChannel accept() throws IOException:接受连接.返回SocketChannel,如果此通道为非阻塞模式,那么此方法可能立即返回,如果有连接请求则返回,否则返回null.非阻塞模式下,此方法将无限期阻塞,知道获得连接请求位置.不管当前ServerSocketChannel为何种阻塞模式,获得的SocketChannel必定为"阻塞模式".在很多情况下,我们不会使用accept方法,而是基于noblocking模式下,获取OP_ACCEPT事件.
ServerSocketChannel channel = ServerSocketChannel.open();
SocketAddress address = new InetSocketAddress(port);
channel.configureBlocking(false);
ServerSocket socket = channel.socket();
socket.setReuseAddress(true);
socket.bind(address);
Selector selector = Selector.open();
selector.keys();
channel.register(selector, SelectionKey.OP_ACCEPT);
while(true){
	Set<SelectionKey> keys = selector.selectedKeys();
	//////if(key.isAcceptable()){....}
}

 

实例参考部分:http://shift-alt-ctrl.iteye.com/blog/1840554

你可能感兴趣的:(SocketChannel)