1. @Slf4j
    2. public class ChannelDemo6 {
    3. public static void main(String[] args) {
    4. try (ServerSocketChannel channel = ServerSocketChannel.open()) {
    5. channel.bind(new InetSocketAddress(8080));
    6. System.out.println(channel);
    7. Selector selector = Selector.open();
    8. channel.configureBlocking(false);
    9. channel.register(selector, SelectionKey.OP_ACCEPT);
    10. while (true) {
    11. int count = selector.select();
    12. // int count = selector.selectNow();
    13. log.debug("select count: {}", count);
    14. // if(count <= 0) {
    15. // continue;
    16. // }
    17. // 获取所有事件
    18. Set<SelectionKey> keys = selector.selectedKeys();
    19. // 遍历所有事件,逐一处理
    20. Iterator<SelectionKey> iter = keys.iterator();
    21. while (iter.hasNext()) {
    22. SelectionKey key = iter.next();
    23. // 判断事件类型
    24. if (key.isAcceptable()) {
    25. ServerSocketChannel c = (ServerSocketChannel) key.channel();
    26. // 必须处理
    27. SocketChannel sc = c.accept();
    28. sc.configureBlocking(false);
    29. sc.register(selector, SelectionKey.OP_READ);
    30. log.debug("连接已建立: {}", sc);
    31. } else if (key.isReadable()) {
    32. SocketChannel sc = (SocketChannel) key.channel();
    33. ByteBuffer buffer = ByteBuffer.allocate(128);
    34. int read = sc.read(buffer);
    35. if(read == -1) {
    36. key.cancel();
    37. sc.close();
    38. } else {
    39. buffer.flip();
    40. debug(buffer);
    41. }
    42. }
    43. // 处理完毕,必须将事件移除
    44. iter.remove();
    45. }
    46. }
    47. } catch (IOException e) {
    48. e.printStackTrace();
    49. }
    50. }
    51. }