import java.io.IOException;import java.net.InetSocketAddress;import java.nio.ByteBuffer;import java.nio.channels.SocketChannel;public class Demo05 {//客户端对象 public static void main(String[] args) throws IOException { //绑定服务器地址和端口 SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9001)); //设置成非阻塞 socketChannel.configureBlocking(false); String msg = "hello nio"; ByteBuffer byteBuffer = ByteBuffer.allocate(msg.getBytes().length); byteBuffer.put(msg.getBytes()); byteBuffer.flip(); socketChannel.write(byteBuffer); socketChannel.close(); }}
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;import java.util.Set;public class Demo04 {//服务器对象 public static void main(String[] args) throws IOException { int port = 9001; //会根据相应的系统调用相应的Selector类 Selector selector = Selector.open(); // 通道 ServerSocketChannel ssc = ServerSocketChannel.open(); // 非阻塞 ssc.configureBlocking(false); //绑定端口 ssc.socket().bind(new InetSocketAddress(port)); //Socket和通道进行绑定 监听获得客户端的链接事件 ssc.register(selector, SelectionKey.OP_ACCEPT); while (true) { //这是一个阻塞方法可以设置时间 没有设置时间会一直阻塞 socket有对应链接过来就会返回 //也就是上面监听的事件 selector.select(); //一个selector可以注册很多通道 这个集合存放的触发事件因为是公用的 其他事件也会存放在里面 Set<SelectionKey> keys = selector.selectedKeys(); //所以用迭代器遍历 Iterator<SelectionKey> it = keys.iterator(); while (it.hasNext()) { //拿到监听的事件 SelectionKey key = it.next(); //判断是不是客户端来的链接 if (key.isAcceptable()) { //获得客户端的通道 SocketChannel sc = ssc.accept(); sc.configureBlocking(false); //给进来的客户端通道绑定事件 READ读 sc.register(selector, SelectionKey.OP_READ); } else if (key.isReadable()) {//如果是读取事件 //获得通道 SocketChannel channel = (SocketChannel) key.channel(); //缓冲区 ByteBuffer byteBuffer = ByteBuffer.allocate(1024); //读取缓冲区大小的内容 放到缓冲区 int len = channel.read(byteBuffer); if (len > 0) { byteBuffer.flip(); System.out.println(new String(byteBuffer.array(), 0, byteBuffer.limit())); } } //清空事件 it.remove(); } } // 服务器监听端口 // 通道 // 非阻塞 // selector // 设置监听 // accept 继续监听 read }}