1. import java.io.IOException;
    2. import java.net.InetSocketAddress;
    3. import java.nio.ByteBuffer;
    4. import java.nio.channels.SocketChannel;
    5. public class Demo05 {
    6. //客户端对象
    7. public static void main(String[] args) throws IOException {
    8. //绑定服务器地址和端口
    9. SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9001));
    10. //设置成非阻塞
    11. socketChannel.configureBlocking(false);
    12. String msg = "hello nio";
    13. ByteBuffer byteBuffer = ByteBuffer.allocate(msg.getBytes().length);
    14. byteBuffer.put(msg.getBytes());
    15. byteBuffer.flip();
    16. socketChannel.write(byteBuffer);
    17. socketChannel.close();
    18. }
    19. }
    1. import java.io.IOException;
    2. import java.net.InetSocketAddress;
    3. import java.nio.ByteBuffer;
    4. import java.nio.channels.SelectionKey;
    5. import java.nio.channels.Selector;
    6. import java.nio.channels.ServerSocketChannel;
    7. import java.nio.channels.SocketChannel;
    8. import java.util.Iterator;
    9. import java.util.Set;
    10. public class Demo04 {
    11. //服务器对象
    12. public static void main(String[] args) throws IOException {
    13. int port = 9001;
    14. //会根据相应的系统调用相应的Selector类
    15. Selector selector = Selector.open();
    16. // 通道
    17. ServerSocketChannel ssc = ServerSocketChannel.open();
    18. // 非阻塞
    19. ssc.configureBlocking(false);
    20. //绑定端口
    21. ssc.socket().bind(new InetSocketAddress(port));
    22. //Socket和通道进行绑定 监听获得客户端的链接事件
    23. ssc.register(selector, SelectionKey.OP_ACCEPT);
    24. while (true) {
    25. //这是一个阻塞方法可以设置时间 没有设置时间会一直阻塞 socket有对应链接过来就会返回
    26. //也就是上面监听的事件
    27. selector.select();
    28. //一个selector可以注册很多通道 这个集合存放的触发事件因为是公用的 其他事件也会存放在里面
    29. Set<SelectionKey> keys = selector.selectedKeys();
    30. //所以用迭代器遍历
    31. Iterator<SelectionKey> it = keys.iterator();
    32. while (it.hasNext()) {
    33. //拿到监听的事件
    34. SelectionKey key = it.next();
    35. //判断是不是客户端来的链接
    36. if (key.isAcceptable()) {
    37. //获得客户端的通道
    38. SocketChannel sc = ssc.accept();
    39. sc.configureBlocking(false);
    40. //给进来的客户端通道绑定事件 READ读
    41. sc.register(selector, SelectionKey.OP_READ);
    42. } else if (key.isReadable()) {//如果是读取事件
    43. //获得通道
    44. SocketChannel channel = (SocketChannel) key.channel();
    45. //缓冲区
    46. ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
    47. //读取缓冲区大小的内容 放到缓冲区
    48. int len = channel.read(byteBuffer);
    49. if (len > 0) {
    50. byteBuffer.flip();
    51. System.out.println(new String(byteBuffer.array(), 0, byteBuffer.limit()));
    52. }
    53. }
    54. //清空事件
    55. it.remove();
    56. }
    57. }
    58. // 服务器监听端口
    59. // 通道
    60. // 非阻塞
    61. // selector
    62. // 设置监听
    63. // accept 继续监听 read
    64. }
    65. }